简体   繁体   English

将 Python 和 Tkinter 的变量插入到 Sqlite3 表中

[英]Insert Variables With Python And Tkinter, Into Sqlite3 Table

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:我尝试将使用 tkinter 条目(python)获得的 sqlite3 表数据插入,但我总是在表中获得空字段。我的代码:

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

I think you should refactoring your code.我认为你应该重构你的代码。

First of all use a naming convention on sql commands, that is, the uppercase首先对sql命令使用一个命名约定,即大写

commands and the rest in lowercase.命令和小写的 rest。

This also for what concerns the code, see pep 8这也与代码有关,请参见 pep 8

I modified your script, in sqlite you don't need to declare an autoincrement field我修改了你的脚本,在 sqlite 你不需要声明一个自动增量字段

if you declare it as primary key.如果您将其声明为主键。

I did not close the cursor and the database to insert more records as you can see如您所见,我没有关闭 cursor 和数据库以插入更多记录

from the attached images.从所附的图片。

And you don't even need to declare Entry if you use textvariable, you can use如果你使用textvariable,你甚至不需要声明Entry,你可以使用

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

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM