Connection Tkinter - Database

Asked

Viewed 190 times

2

Good night! Guys, I’m starting in the world of programming and today I was following a tutorial that for me didn’t work and I don’t know how to solve the problem, I tried everything. This is to define a function of a button that sends the data from a login screen to the database. Below:

def Armazenar():
    nome = NomeEntry.get()
    email = EmailEntry.get()
    usuario = UserEntry.get()
    senha = PassEntry.get()
    Db_Login.cursor.execute("insert into usuarios(Nome, E_mail, Login, Senha)
    values(?, ?, ?, ?)", (nome, email, usuario, senha))
    Db_Login.conexão.commit()

Creating Record Button

RegistrarButton = ttk.Button(RightFrame, text="Registrar", width=35, command=Armazenar)

When I click on the function button, it shows the following errors:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\celio\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)

File "C:/Users/celio/PycharmProjects/TKINTER/INDEX.py", line 66, in Armazenar
    values(?, ?, ?, ?)""", (nome, email, usuario, senha))

File "C:\Users\celio\PycharmProjects\cursopython\venv\lib\site-packages\pymysql\cursors.py", line 168, in execute
    query = self.mogrify(query, args)

File "C:\Users\celio\PycharmProjects\cursopython\venv\lib\site-packages\pymysql\cursors.py", line 147, in mogrify
    query = query % self._escape_args(args, conn)
TypeError: not all arguments converted during string formatting

1 answer

1


TLDR; "pymysql" driver uses sequence %s (or %d, %f, etc...) to insert arguments into queries, and not ?. Exchange the ? for %s that will work.

Explaining The Python language has a specification of how SQL drivers, for any database, should work, to PEP 249 - this specification speaks for example, that everyone has to have the call connect, that the connecting object has to have a method .execute, which is what executes the queries and etc... However this same specification leaves free some 5 or 6 different ways of how is made marking the parameters that will be replaced in the queries.

The "sqlite3" that accompanies Python simply uses question marks - ? - as it is now in your code. Only pymysql uses the marking with %s (as used for string substitutions with the operator %, which in turn uses the same notation as the printf of the C language).

In this other answer I wrote these days I talk more about it: Mount SQL query in Python3 from data in a dictionary

(in particular, of interest to the case, the driver has a variable called "paramstyle" that says what type of markup is expected for the queries' arguments - check in https://www.python.org/dev/peps/pep-0249/#paramstyle)

Mount SQL query in Python3 from data in a dictionary

Browser other questions tagged

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