ThLez ThLez - 1 year ago 137
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)
data = cursor.fetchall()


and result >

Select Row : dt
Number row 1-10 : 1
Traceback (most recent call last):
File "./", line 12, in <module>
File "build/bdist.linux-x86_64/egg/mysql/connector/", line 515, in execute
File "build/bdist.linux-x86_64/egg/mysql/connector/", line 488, in cmd_query
File "build/bdist.linux-x86_64/egg/mysql/connector/", 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download