在py3上,我使用pymysql模块连接MySQL。
我将函数编写到Database()类中,其中MySQLi在构造函数上运行:
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()
运行py database.php后显示此错误:(:
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")
答案 0 :(得分:1)
使用字符串插值构建查询时,可以获得转义/ quoiting问题,但是使用参数化查询很容易:
sql = "INSERT INTO `users` (`id`, `first_name`) VALUES (%s, %s)"
cursor.execute(sql, (id, first_name)