简体   繁体   English

MySQL Python:JSON 类型在赋值时引发错误

[英]MySQL Python: JSON type throws error on assignment

I am unable to update JSON type cells with ON DUPLICATE KEY UPDATE , as an error is thrown.由于抛出错误,我无法使用ON DUPLICATE KEY UPDATE更新 JSON 类型的单元格。 I am using mysql-connector-python .我正在使用mysql-connector-python Here is a minimal (not)working example:这是一个最小(非)工作示例:

First, I define my table as:首先,我将我的表定义为:

cursor = db.cursor()
cursor.execute('''
    CREATE TABLE test (
        id INT AUTO_INCREMENT PRIMARY KEY,
        foo VARCHAR(255) NOT NULL UNIQUE,
        bar JSON NOT NULL
    )
''')

Then I try to insert values into the table:然后我尝试将值插入表中:

val = [
    {
        'foo': 'lorem ipsum',
        'bar': json.dumps({'a': 1}),
    },
    {
        'foo': 'dolor sit amet',
        'bar': json.dumps({'a': 2}),
    },
]
sql = '''
    INSERT INTO test
        (foo, bar)
    VALUES
        (%(foo)s, %(bar)s)
    ON DUPLICATE KEY UPDATE 
        bar = %(bar)s
'''
cursor = db.cursor()
cursor.executemany(sql, val)

Which leads to an error:这导致错误:

ProgrammingError: 1064 (42000): 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 '%(bar)s' at line 6

If I change the line that says bar = %(bar)s to bar = \\'%(bar)s\\' , the code happily executes... at least for the first time, until I run this section again to invoke the ON DUPLICATE KEY UPDATE clause, which then results in another error:如果我将bar = %(bar)s更改为bar = \\'%(bar)s\\' ,代码会愉快地执行......至少第一次,直到我再次运行本节以调用ON DUPLICATE KEY UPDATE子句,然后导致另一个错误:

DataError: 3140 (22032): Invalid JSON text: "Invalid value." at position 0 in value for column 'test.bar'.

Could you, please, advise me how to fix my syntax?你能告诉我如何修复我的语法吗?

You could use the VALUES function in the UPDATE clause as well:您也可以在 UPDATE 子句中使用VALUES函数

In assignment value expressions in the ON DUPLICATE KEY UPDATE clause, you can use the VALUES(col_name) function to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement.在 ON DUPLICATE KEY UPDATE 子句中的赋值表达式中,您可以使用 VALUES(col_name) 函数来引用来自 INSERT ... ON DUPLICATE KEY UPDATE 语句的 INSERT 部分的列值。 In other words, VALUES(col_name) in the ON DUPLICATE KEY UPDATE clause refers to the value of col_name that would be inserted, had no duplicate-key conflict occurred.换句话说,ON DUPLICATE KEY UPDATE 子句中的 VALUES(col_name) 是指将插入的 col_name 的值,没有发生重复键冲突。 This function is especially useful in multiple-row inserts.此函数在多行插入中特别有用。

sql = '''
    INSERT INTO test
        (foo, bar)
    VALUES
        (%(foo)s, %(bar)s)
    ON DUPLICATE KEY UPDATE 
        bar = VALUES(bar)
'''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM