MysqlDB 在尝试插入时将单引号附加到字符串
MysqlDB appends single quotes to string when trying to insert
我一直在不知疲倦地尝试解决在 python 中使用参数化 mysql 查询的问题,但还没有找到解决方案。
我想做的是一件简单的事情:-
def parameterized_dml_query(self, sql, param):
print sql, param
cursor = self.connection.cursor()
b='wtf'
cursor.execute("""insert into table(schema_name) values %s""", (b,))
self.connection.commit()
logger.info("Row(s) were updated/ inserted :%s for sql : %s",str(cursor.rowcount), sql)
no_of_rows_update = str(cursor.rowcount)
return no_of_rows_update
但我总是遇到这个错误:
(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 ''wtf'' at line 1")
我不知道为什么这...API 正在为其添加单引号。
其他问题:-
1. 有什么方法可以参数化table_name。
2. 如果我有一个值列表,如
,则插入 NULL
list_of_keys = ''.join(['key1','key2','key3'])
list_of_values =''.join(['v1', None, 'v2'])
sql = """insert into table(%s) values %s"""
param = (list_of_keys, list_of_values)
我调用 parameterized_dml_query
函数它不起作用。那么处理 None.
的最佳方法是什么?
您有 sql 语法错误。您忘记了值后的括号。 table
也是保留字。我会用反引号引用。请改用以下内容:
cursor.execute("""insert into `table`(schema_name) values (%s)""", (b,))
此外,您不能将字段作为参数传递。您可以使用:
list_of_keys = ''.join(['key1','key2','key3'])
sql = """insert into `table`(%s) values (%%s)""" % list_of_keys
cursor.execute(sql, ['v1', None, 'v2'])
我一直在不知疲倦地尝试解决在 python 中使用参数化 mysql 查询的问题,但还没有找到解决方案。
我想做的是一件简单的事情:-
def parameterized_dml_query(self, sql, param):
print sql, param
cursor = self.connection.cursor()
b='wtf'
cursor.execute("""insert into table(schema_name) values %s""", (b,))
self.connection.commit()
logger.info("Row(s) were updated/ inserted :%s for sql : %s",str(cursor.rowcount), sql)
no_of_rows_update = str(cursor.rowcount)
return no_of_rows_update
但我总是遇到这个错误:
(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 ''wtf'' at line 1")
我不知道为什么这...API 正在为其添加单引号。
其他问题:- 1. 有什么方法可以参数化table_name。 2. 如果我有一个值列表,如
,则插入 NULLlist_of_keys = ''.join(['key1','key2','key3'])
list_of_values =''.join(['v1', None, 'v2'])
sql = """insert into table(%s) values %s"""
param = (list_of_keys, list_of_values)
我调用 parameterized_dml_query
函数它不起作用。那么处理 None.
您有 sql 语法错误。您忘记了值后的括号。 table
也是保留字。我会用反引号引用。请改用以下内容:
cursor.execute("""insert into `table`(schema_name) values (%s)""", (b,))
此外,您不能将字段作为参数传递。您可以使用:
list_of_keys = ''.join(['key1','key2','key3'])
sql = """insert into `table`(%s) values (%%s)""" % list_of_keys
cursor.execute(sql, ['v1', None, 'v2'])