3

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.

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
4
  • How are you executing this query?
    – tadman
    Apr 18, 2016 at 16:58
  • cursor.execute(query_publisher, args_publisher) -- I'm using this in both cases. Apr 18, 2016 at 17:05
  • I'm not as familiar with Python, but if it's like Perl then you may have args_publisher being a scalar instead of a list type. Is there any reason you're doing this with intermediate variables rather than directly? Would (publisher_name,) to force it as a list fix the issue?
    – tadman
    Apr 18, 2016 at 17:07
  • Ah. That's a cool idea. I think I have to do it this way to use mysql.connector; I tried a simple version of your suggestion and it's not working, but I'll play with that, thanks! I'd still like to know why the top one works and the second one doesn't (now I'm googling about scalar vs. list types!) Apr 18, 2016 at 17:14

1 Answer 1

4

the syntax for Mysql execute is 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

1
  • Thanks so much, haifzhan. That did it. I think tadman was on the right track in a way, then--I was supposed to be supplying a tuple. Thanks again everybody! Apr 18, 2016 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.