本文介绍了pymysql 返回错误 SQL 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 py3 上,我使用 pymysql 模块连接到 MySQL.

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

我像这样将函数写入 Database() 类,其中 MySQLi 在构造函数上运行:

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()

在我运行 py database.php 后,它显示此错误 :( :

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")

推荐答案

当您使用字符串插值构建查询时,您可能会遇到转义/引用问题,但是使用参数化查询很容易:

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)

这篇关于pymysql 返回错误 SQL 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-11 23:09