Sorry this is my first post. I try to insert data into a sqlite3 table that I get using tkinter entries (Python).
But I always get empty columns in the table.
This is my code:
import sqlite3
from tkinter import *
def data_entry():
CDB.execute('insert into CUSTOMERS (NAME, CODE) VALUES (?, ?)', (NAME_E, CODE_E))
DB.commit()
CDB.close()
DB.close()
X=Tk()
NAME=StringVar()
CODE=StringVar()
DB=sqlite3.connect('DB.db')
CDB=DB.cursor()
CDB.execute('''create table if not exists CUSTOMERS
(ID integer primary key autoincrement,
NAME text(20), CODE text(10))''')
NAME_E=Entry(X,textvariable=NAME).pack()
CODE_E=Entry(X,textvariable=CODE).pack()
SAVE=Button(X,text='SAVE',command=data_entry).pack()
X.mainloop()
I think you should refactoring your code.
First of all use a naming convention on sql commands, that is, the uppercase
commands and the rest in lowercase.
This also for what concerns the code, see pep 8
I modified your script, in sqlite you don’t need to declare an autoincrement field
if you declare it as primary key.
I did not close the cursor and the database to insert more records as you can see
from the attached images.
And you don’t even need to declare Entry if you use textvariable, you can use
these directly to pass the values.
#!/usr/bin/python3
import tkinter as tk
import sqlite3 as lite
def data_entry():
sql = "INSERT INTO customers (customer,code)VALUES(?,?)"
args = (customer.get(),code.get())
print(sql, args)
cur.execute(sql, args)
dbms.commit()
sql = "SELECT * FROM customers"
cur.execute(sql)
rs = cur.fetchall()
for i in rs:
print(i)
#cur.close()
#dbms.close()
tk.X=tk.Tk()
customer = tk.StringVar()
code = tk.StringVar()
dbms = lite.connect('DB.db')
cur = dbms.cursor()
sql = "CREATE TABLE IF NOT EXISTS customers (customer_id INTEGER PRIMARY KEY, customer TEXT, code TEXT);"
cur.execute(sql)
tk.Entry(tk.X,textvariable=customer).pack()
tk.Entry(tk.X,textvariable=code).pack()
tk.Button(tk.X, text="Save", command=data_entry).pack()
tk.X.mainloop()