Using Tkinter together with a database

Asked

Viewed 701 times

0

I am doing a program of registration of people with interface (still very basic, just to do tests) and I am with several difficulties:

  • I’m extracting the data using the .get(), however, I can only type 1 character. If I type more the following error appears: Incorrect number of bindings supplied. The Current statement uses 1, and there are 2 supplied.

Code:

from tkinter import *
import sqlite3
import time
import datetime




connection = sqlite3.connect('Main_9_DB.db')
c = connection.cursor()

def create_table():
    c.execute('CREATE TABLE IF NOT EXISTS teste (ed text)')

create_table()



def dataentry():

    c.execute('INSERT INTO teste (ed)VALUES (?)',(ed.get()))
    connection.commit()





def bt_onclick():
   # print(ed.get())
    dataentry()

janela = Tk()
var = StringVar()   
ed = Entry(janela, bd = 2, textvariable = var)
ed.place(x = 50, y = 100)

bt = Button(janela, width=20, text="OK", command=bt_onclick)
bt.place(x = 50, y = 150)

lb = Label(janela, text="Label")
lb.place(x = 100, y = 200)


janela.geometry("300x300+300+300")
janela.mainloop()

If you can answer me, I’d be grateful.

1 answer

1

It is because the second parameter of the execute - where you are passing "ed.get()", must be a sequence - that is, even if you will only use a substitution in the query (which is the case, you only have a "(?)" in your string), that parameter should normally be a list or a tuple, with the values you want to replace in.

Since in Python a string is a valid sequence, when you do not put the string returned by get within a list or a tuple, it passes each character of the string as an element of the sequence. So with a single letter it works - but with two or more letters, it says it has extra parameters.

It’s easy to see when we use the "Join" method of strings - it also expects a string, and if we pass a string, it does the same thing: it treats each element of the string as a sequence item:

In [47]: ",".join("teste")
Out[47]: 't,e,s,t,e'

The correct is:

In [48]: ",".join(("teste",))
Out[48]: 'teste'

What is essential here is the , right after the string - in this way Python understands that this inside parentheses is "a tuple with a single element", not "a parentheses around the string" - which is what happens in your code.

If you do not want to depend on this "," you can pass your parameter to run it as a list - in this case, the extra comma is not necessary. That is - change your "run" line to look like below:

def dataentry():

    c.execute('INSERT INTO teste (ed) VALUES (?)',[ed.get()])
    connection.commit()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.