Using Tkinter next to a Database

0

I'm doing a people registration program with interface (still pretty basic, just to do tests) and I'm having several difficulties:

  • I am extracting the data using .get() , however, I can only type 1 character. If I type more then 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'm grateful.

    
asked by anonymous 04.07.2018 / 20:27

1 answer

0

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

As in Python a string is a valid string, 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 string. So with a single letter it works - but with two or more letters, it says it has more parameters.

It is 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: treats each element of the string as an item in the string:

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

The correct one is:

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

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

If you do not want to depend on this "," you can pass your parameter to run as a list - in that case, the extra comma is not required. That is - change the line of your "execute" to be as below:

def dataentry():

    c.execute('INSERT INTO teste (ed) VALUES (?)',[ed.get()])
    connection.commit()
    
04.07.2018 / 20:45