ThLez ThLez - 1 month ago 29
Python Question

I want to select data in mysql from python

I made input data for select data in mysql but result error can't select data. i don't know don't understand problem

conn = mysql.connector.connect(host="",user="",passwd="",db="")
cursor = conn.cursor()

num0 = raw_input("Select Row : ")
num1 = int(input("Number row 1-10 : "))

if num0 and num1 <= 10:
sqlde0 = "SELECT * FROM '%s' WHERE user1 = '%d' " %(num0,num1)
cursor.execute(sqlde0)
data = cursor.fetchall()
print(data[0])


conn.close()


and result >

Select Row : dt
Number row 1-10 : 1
Traceback (most recent call last):
File "./sql.py", line 12, in <module>
cursor.execute(sqlde0)
File "build/bdist.linux-x86_64/egg/mysql/connector/cursor.py", line 515, in execute
File "build/bdist.linux-x86_64/egg/mysql/connector/connection.py", line 488, in cmd_query
File "build/bdist.linux-x86_64/egg/mysql/connector/connection.py", line 395, in _handle_result
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''dt' WHERE user1 = '1'' at line 1

Answer

You should remove the quotes from around the table name - quotes are used to denote string literals, not object names. Additionally, numeric literals do not have quotes around them, so you should remove those too:

sqlde0 = "SELECT * FROM %s WHERE user1 = %d " %(num0,num1)
# Here -----------------^ And here ------^

BTW, note that using string manipulation to construct an SQL statement may make your program vulnerable to SQL injection attacks. You should consider using prepared statements instead.