python mysql在只有一个变量时插入语法错误

时间:2021-09-16 02:05:38

I'm using Python 2, if that matters for this issue. I'm playing with mysql.connector as a learning exercise, and had built some working inserts, then came across an odd (to me) problem--I'm sure I'm doing something wrong that is simple. I was inserting into two columns for a few tables, something like the first example, below; when I had a case where I was inserting into just one column, I got a syntax error.

我使用的是python2,如果这对这个问题很重要的话。我玩mysql。connector作为一个学习练习,并且构建了一些工作插入,然后遇到了一个奇怪的(对我来说)问题——我确信我做错了一些简单的事情。我为一些表插入了两列,如下面的第一个例子;当我在一个列中插入一个例子时,我得到一个语法错误。

Any ideas why syntax like this works just fine:

有什么想法可以解释这样的语法吗?

    query_publisher =   "INSERT INTO publisher (name, name2) "\
                    "VALUES (%s, %s) " \
                    "ON DUPLICATE KEY UPDATE PUBLISHER_ID=LAST_INSERT_ID(PUBLISHER_ID)"
    args_publisher = (publisher_name, publisher_name2)

Yet this syntax, which is what I really want to do, throws a syntax error:

然而,这个语法,我真正想做的,抛出了一个语法错误:

    query_publisher =   "INSERT INTO publisher (name) "\
                    "VALUES (%s) " \
                    "ON DUPLICATE KEY UPDATE PUBLISHER_ID=LAST_INSERT_ID(PUBLISHER_ID)"
    args_publisher = (publisher_name)

[EDIT]: In both cases I'm executing this with:

[编辑]:在这两种情况下,我都是这样执行的:

        cursor.execute(query_publisher, args_publisher)

The error:

错误:

1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%s ON DUPLICATE KEY UPDATE PUBLISHER_ID=LAST_INSERT_ID(PUBLISHER_ID)' at line 1

1 个解决方案

#1


3  

the syntax for Mysql execute is execute(query_statement, tuple_values)

Mysql执行的语法是execute(query_statement, tuple_values)

args_publisher = (publisher_name) should be tuple, when it is one-element tuple, it should be (publisher_name,) Don't omit the comma

args_publisher = (publisher_name)应该是tuple,当它是一个元素元组时,它应该是(publisher_name,)不要省略逗号

#1


3  

the syntax for Mysql execute is execute(query_statement, tuple_values)

Mysql执行的语法是execute(query_statement, tuple_values)

args_publisher = (publisher_name) should be tuple, when it is one-element tuple, it should be (publisher_name,) Don't omit the comma

args_publisher = (publisher_name)应该是tuple,当它是一个元素元组时,它应该是(publisher_name,)不要省略逗号