I have a CRUD form with entries and 4 button for deleting, updating, creating, getting values from my database, I want to implement another button to open an imagen which is binded to my id entry also able to works with my deleting, updating, creating, getting buttons, I've been trying to use BLOB and I'm able to save an image in my database as BLOB. Actually I understand that I need to create textvariables for my entries like 'idvar = StringVar() , namevar = Stringvar()..., etc', So I'm not sure how to do it for an image label in order to work with my CRUD buttons deleting, updating, creating, getting
This is my code I got so far and it's working well saving images into my photos columns:
from tkinter import *
import sqlite3
top = Tk()
top.configure(width='444', heigh='400')
conn = sqlite3.connect('test.db')
c = conn.cursor()
def enterdata():
id = 'hello'
photo = convert_pic()
c.execute('INSERT INTO test (id, photo) VALUES (?, ?)', (id, photo)) #Here my id has integer value and my photo has BLOB value in my database
conn.commit()
def convert_pic():
filename = 'images/image6.jpg'
with open(filename, 'rb') as file:
photo = file.read()
return photo
btn = Button(top, text='save photo', command=enterdata)
btn.place(x='100', y='111')
mainloop()
Now that you have the BLOB you can use io.BytesIO. I will create an example to demonstrate, like:
from PIL import Image, ImageTk
from io import BytesIO
def show(data):
img_byte = BytesIO(data)
img = ImageTk.PhotoImage(Image.open(img_byte))
Label(root,image=img).pack()
root.image = img # Keep a reference
So now you can query the database and fetch the value:
def fetch():
c = con.cursor()
id = 1 # Any id
c.execute('SELECT photo FROM test where id=?',(id,))
data = c.fetchall()[0][0] # Get the blob data
show(data) # Call the function with the passes data
This will show the image in a label in the root window for the entered id.
Related
I want to retrieve images stored in data tables using python jupyter notebook and save them in desktop folder but unable to understand where I'm doing mistake.
def write_file(data, filename):
# Convert binary data to proper format and write it on Hard Disk
with open(filename, 'wb') as file:
file.write(data)
cursor.execute("SELECT * from mydb where id = {0}")
record = cursor.fetchall()
for row in record:
ID= row[0]
print("Id = ", row[0])
image = row[1]
photo= r"C:\Users\my_profile\Desktop\outputimage\img{0}.JPG".format(str(ID))
write_file(image, photo)
How to read CSV file in mysql databse using Django.
I want to read csv file data using django and write this csv data in MySQL Databases.
Take a look at django-import-export, which covers exactly this use case.
here is the solution whatever i understand from your question
First of all create browse button for user to take CSV file as a input and then store it temprory in apps's static/upload folder.Then pass the path of that file to our datastore function present in views.py.
forms.py
from django import forms
class browse(forms.Form):
file = forms.FileField()
views.py
import csv
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
def index(request):
result = None
form = None
if request.method == 'POST':
form = browse(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file']) # store file in upload folder
path = "static/upload/"+ str(request.FILES['file'])#path of selected file
with open(path,'rt')as f:
data = csv.reader(f)
for row in data:
storedata(row)
else:
pass
def storedata(row):
connection = mysql.connector.connect(host='localhost',
database='electronics',
user='root',
password='root')
mySql_insert_query = """INSERT INTO Laptop (name, fname, lname)
VALUES
(row[0], row[1], row[2]) """
cursor = connection.cursor()
cursor.execute(mySql_insert_query)
connection.commit()
print(cursor.rowcount, "Record inserted successfully into Laptop table")
cursor.close()
models.py
from django.db import models
def handle_uploaded_file(f):
with open('static/upload/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
import lot_details, car_details
import numpy as np
import sqlite3
conn = sqlite3.connect('parkingLot.db')
c = conn.cursor()
class Parking(object):
"""
Parking class which has details about parking slots
as well as operation performed on parking are present here
"""
def __init__(self):
self.slots = {}
def create_parking_lot(self, no_of_slots):
try:
c.execute('CREATE TABLE IF NOT EXISTS parkingTable(slot_no REAL, reg_no TEXT, colour TEXT, total_time TEXT,charge TEXT)')
except Exception as ex:
print("Couldn't make a table in DB")
no_of_slots = int(no_of_slots)
if len(self.slots) > 0:
print ("Parking Lot already created")
return
if no_of_slots > 0:
for i in range(1, no_of_slots+1):
temp_slot = lot_details.PSlot(slot_no=i, available=True)
self.slots[i] = temp_slot
print ("Created a parking lot with {} slots" .format(no_of_slots))
else:
print ("Number of slots provided is incorrect.")
return
Using above code I am trying to create a database(which is successful) but now I am not able to create the Table inside it using the above command.
I tried doing it separately its working there. But, I am not able to create it using above code.
Depending on how and where you are creating the Parking object I suspect this could be a scoping issue, either pass the db connection into the constructor or just create it in the constructor itself. Code modified for brevity. The following works for me.
import sqlite3
class Parking(object):
def __init__(self):
self.slots = {}
self.conn = sqlite3.connect('parkingLot.db')
def create_parking_lot(self, no_of_slots):
try:
cur = self.conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS parkingTable(slot_no REAL, reg_no TEXT, colour TEXT, total_time TEXT,charge TEXT)')
except Exception as ex:
print("Couldn't make a table in DB")
return
parking = Parking()
parking.create_parking_lot(5)
I wonder if it is possible to store in variables the contents from a tree widget row (when it is selected with the mouse) see picture. Basically I want to sync my tree with a database, every time when I insert or delete an element in my tree, my database needs to auto update.
With the insert part it is not a problem , because I have entry widgets, but I don't know how to manage the delete part. Therefore, I wonder if it is possible to do this with some cursor selection function.
I have been trying for a very long time to find a solution for this, I would really appreciate if someone can help me with some hints
Code:
import tkinter
from tkinter import ttk
class cards(tkinter.Frame):
def __init__(self, parent):
tkinter.Frame.__init__(self, parent)
self.parent=parent
self.parent.geometry("800x500")
self.initialize_user_interface()
def initialize_user_interface(self):
self.parent.title("cards")
self.parent.grid_rowconfigure(0,weight=1)
self.parent.grid_columnconfigure(0,weight=1)
self.parent.config(background="lavender")
self.Card_label = tkinter.Label(self.parent, text = "Card type:")
self.Card_entry = tkinter.Entry(self.parent)
self.Card_label.place(x=5,y=5)
self.Card_entry.place(x=70,y=5)
self.SN_label = tkinter.Label(self.parent, text = "SN:")
self.SN_entry = tkinter.Entry(self.parent)
self.SN_label.place(x=5,y=40)
self.SN_entry.place(x=70,y=40)
self.submit_button = tkinter.Button(self.parent, text = "Insert", command = self.insert_data)
self.submit_button.place(x=210,y=15)
self.exit_button = tkinter.Button(self.parent, text = "Exit", command = self.exit)
self.exit_button.place(x=270,y=15)
self.tree = ttk.Treeview( self.parent, columns=('Card Type', 'SN'))
self.tree.heading('#0', text='Nr.')
self.tree.heading('#1', text='Card Type')
self.tree.heading('#2', text='SN')
self.tree.column('#1', stretch=tkinter.YES)
self.tree.column('#2', stretch=tkinter.YES)
self.tree.column('#0', stretch=tkinter.YES)
self.tree.place(x=0,y=100)
self.treeview = self.tree
self.i = 1
def exit(self):
self.master.destroy()
def insert_data(self):
self.treeview.insert('', 'end', text=str(self.i), values=(self.Card_entry.get(), self.SN_entry.get()))
self.i = self.i + 1
def main():
root=tkinter.Tk()
d=cards(root)
root.mainloop()
if __name__=="__main__":
main()
You can use
for item in self.tree.selection():
print(self.tree.item(item, "text"))
print(self.tree.item(item, "values"))
#print(self.tree.item(item))
to see data from all selected rows - you can select more than one row.
You can use it in function assigned to button
or you can use bind() to assign function to mouse click on row.
I'm trying to use Twitter's Streaming API to save tweets to a database using sqlite3. The problem is my database comes back empty. I'm using DB Browser for SQLIte to check the schema and the table and columns are there but no values for any column. Any thoughts?
#create sql table
conn = sqlite3.connect('twitter_one5.db')
c = conn.cursor()
c.execute('''CREATE TABLE tweets
(coordinates integer,
place text)''')
conn.commit()
conn.close()
# open connection
conn = sqlite3.connect('twitter_one5.db')
c = conn.cursor()
Create a class to handle inserting tweet info into database:
class Tweet():
# data from tweet
def __init__(self, coordinates, place):
self.coordinates = coordinates
self.place = place
# insert data from tweet into DB
def insertTweet(self):
c.execute("INSERT INTO tweets (coordinates, place) VALUES(?, ?)",
(self.coordinates, self.place))
conn.commit()
Create a tweet listener using the Streaming API:
class listener(tweepy.StreamListener):
def on_status(self, status):
tweet_data = Tweet(status.coordinates, status.place)
tweet_data.insertTweet()
print('inserted')
Create instance of listener and filter for keywords:
l = listener()
stream = tweepy.Stream(auth, l)
stream.filter(track=['twitter'])