【问题标题】:MysqlDB appends single quotes to string when trying to insertMysqlDB在尝试插入时将单引号附加到字符串
【发布时间】:2015-10-13 00:55:19
【问题描述】:

我一直在不知疲倦地尝试解决在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 的最佳方法是什么。

【问题讨论】:

    标签: python mysql mysql-python


    【解决方案1】:

    您有 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'])
    

    【讨论】:

    • 如果我传递多个参数失败,例如: cursor.execute("""insert into table1(%s) values (%s)""", (query_columns,query_values,)) bcoz它附加了'单引号 mysqlerror 1064 :'source_schema_name') values ('wtf')'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2015-07-01
    • 1970-01-01
    相关资源
    最近更新 更多