0

Sorry this is my first post. I try to insert into sqlite3 table datas that i get using tkinter entries (python) but i always obtain empty fields in the table.my code:

import sqlite3

from tkinter import *

def data_entry():

   CDB.execute('insert into COSTUMERS (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 COSTUMERS
                (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()
Itai Klapholtz
  • 196
  • 1
  • 2
  • 15
Tommy
  • 101
  • 8

1 Answers1

0

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()

enter image description here

enter image description here

enter image description here

1966bc
  • 1,148
  • 1
  • 6
  • 11
  • thx for answer. it prints correctly, but table is not updated. it gives no new fields, no NULL fields, no empty new fields – Tommy Nov 15 '20 at 11:08
  • 1
    Hi, I,ve update the answar with the image of my db that is correctly update. – 1966bc Nov 15 '20 at 12:01