Riley
Riley

Reputation: 4812

Why am I getting a SQL Syntax Error in python

Hi I'm trying to insert some data into a MySQL database. However I keep getting a syntax error from the MySQL.connector. I'm not sure what is causing this I've tried all the examples on the mysql website but none of them work. I could get this to work on my old web server for a different website but now its not working.

My code is (the ID is a 30 string of upper-case letters and numbers and the UserID is a 20 digit string):

sql = '''INSERT INTO LoginSessions(SessionID,UserID) VALUES({0},{1})'''.format(ID,UserID)
cursor.execute(sql)

This is the error I keep getting:

<class 'mysql.connector.errors.ProgrammingError'>: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''ORPFDQE0CKYVY1LN0RPW',))' at line 1 

Thanks for any help in advance. It will be greatly appreciated it's been bugging me for a few hours. I've tried everything I possibly know and am about to give up!

Upvotes: 1

Views: 3899

Answers (1)

Daniel
Daniel

Reputation: 42748

You shouldn't use format to create a sql-command, use placeholders, then you don't have to take care, that the types of your IDs is correctly encoded:

sql = '''INSERT INTO LoginSessions(SessionID,UserID) VALUES(%s,%s)'''
cursor.execute(sql, (ID,UserID))

Upvotes: 1

Related Questions