pymysql return error SQL syntax

2019-07-29 17:31发布

问题:

On py3, i use pymysql module for connecting to MySQL.

i write function into Database() class like this where MySQLi run on constructor:

def add_user_to_database(self, id, first_name, last_name, username, lang_code):
    with self.MySQLi.cursor() as cursor:
        cursor.execute('INSERT INTO users (id, first_name, last_name, username, language_code) VALUES ({0}, {1}, {2}, {3}, {4})'.format(id, first_name, last_name, username, lang_code))
    connection.commit()

after i run py database.php it show this error :( :

    raise errorclass(errno, errval)
pymysql.err.ProgrammingError: (1064, "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 ' sepwhrr, en)' at line 1")

回答1:

When you build a query with string interpolation, you can get escape/quoiting issues, however it's easy to use a parametrised query:

sql = "INSERT INTO `users` (`id`, `first_name`) VALUES (%s, %s)"
cursor.execute(sql, (id, first_name)