1
nameEnt = nameEntered.get()

print(nameEnt)

sql = "SELECT * FROM attendance WHERE name="%s"
val = (nameEnt)
print(mycursor.execute(sql, val))
myresult = mycursor.fetchall()
for x in myresult:
    print(x)

I would like to pass the string in 'nameEnt' into the SQL query using python. I'm currently using the mysql-connector package. The program keeps telling me that my syntax is incorrect. I can execute the query in SQL directly without any problem.

I have also tried

sql = "SELECT * FROM attendance WHERE name= "+nameENt
eeshankeni
  • 240
  • 3
  • 11
  • 1
    You have an issue with your `"`... Syntax highlighting will give you a hint. ;) try: `"SELECT * FROM attendance WHERE name=%s"` – Thomas Aug 11 '21 at 14:35
  • 1
    Have a look at the [official docs](https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html) – Maurice Meyer Aug 11 '21 at 14:36
  • 1
    You don't need quotes around `%s` if you're passing a query parameter separately. – khelwood Aug 11 '21 at 14:38

2 Answers2

1

Do not combine SQL strings with data unless you know what you are doing. Doing so is a sure way to get yourself an SQL injection vulnerability.

Your original code was almost correct. First, as the comments noted, you don't need the quotes around %s:

sql = "SELECT * FROM attendance WHERE name=%s"

Then, your second parameter to cursor.execute() is a tuple, but in Python, to make a single-element tuple, wrapping it in brackets isn't enough:

my_element = 12345
not_a_tuple = (my_element)
type(not_a_tuple) == int

real_tuple = (my_element,)  # note the comma at the end
type(real_tuple) == tuple

Applying these to your code, you get:

nameEnt = nameEntered.get()

print(nameEnt)

sql = "SELECT * FROM attendance WHERE name=%s"
val = (nameEnt,)
print(mycursor.execute(sql, val))
myresult = mycursor.fetchall()
for x in myresult:
    print(x)
Danya02
  • 1,006
  • 1
  • 9
  • 24
1

you can try:

sql = "SELECT * FROM attendance WHERE name = %s",(nameEnt)

Or:

sql = "SELECT * FROM attendance WHERE name = {}".format(nameEnt)
JulianBPL
  • 149
  • 1
  • 10
  • 1
    -1, because this allows SQL injection -- if I make it so that `nameEnt` becomes `'' or 1=1` (which I can probably do because this is a value received from the outside), then the app will return information about every record in the table, and if you craft the query more carefully then you might even be able to delete data from the database and such like. Don't take this risk, use parameters properly -- my answer shows how. – Danya02 Jul 05 '22 at 07:48