Python "INSERT INTO"与 "INSERT INTO...ON DUPLICATE KEY UPDATE"

标签 python mysql

我正在尝试使用 python 将记录插入 MySQL 数据库,然后更新该记录。为此,我创建了 2 个函数:

def insert_into_database():

query = "INSERT INTO pcf_dev_D.users(user_guid,username) VALUES (%s, %s) "
data = [('1234', 'user1234')]
parser = ConfigParser()
parser.read('db/db_config.ini')
db = {}
section = 'mysql'

if parser.has_section(section):
    items = parser.items(section)
    for item in items:
        db[item[0]] = item[1]
else:
    raise Exception('{0} not found in the {1} file'.format(section, filename))

try:
    conn = MySQLConnection(**db)
    cursor = conn.cursor()
    cursor.executemany(query, data)
    conn.commit()
except Error as e:
    print('Error:', e)
finally:
    # print("done...")
    cursor.close()
    conn.close()

这工作正常并将 1234、user1234 插入到数据库中。

现在我想将这个特定用户的用户名更新为“5678”,所以我创建了另一个函数:

def upsert_into_database():

query = "INSERT INTO pcf_dev_D.users(user_guid,username) " \
        "VALUES (%s, %s) ON DUPLICATE KEY UPDATE username='%s'"
data = [('1234', 'user1234', 'user5678')]
parser = ConfigParser()
parser.read('db/db_config.ini')
db = {}
section = 'mysql'

if parser.has_section(section):
    items = parser.items(section)
    for item in items:
        db[item[0]] = item[1]
else:
    raise Exception('{0} not found in the {1} file'.format(section, 'db/db_config.ini'))

try:
    conn = MySQLConnection(**db)
    cursor = conn.cursor()
    cursor.executemany(query, data)
    conn.commit()
except Error as e:
    print('Error:', e)
finally:
    # print("done...")
    cursor.close()
    conn.close()

这会产生以下错误: 错误:SQL 语句中未使用所有参数

有趣的是,如果我将查询和数据修改为:

query = "INSERT INTO pcf_dev_D.users(user_guid,username) " \
        "VALUES (%s, %s) ON DUPLICATE KEY UPDATE username='user5678'"
data = [('1234', 'user1234')]

然后 python 更新记录就好了......我错过了什么?

最佳答案

您在 update 子句中将第三个参数包含在单引号内,因此它被解释为字符串的一部分,而不是参数的占位符。您不能用引号将参数括起来:

query = "INSERT INTO pcf_dev_D.users(user_guid,username) " \
        "VALUES (%s, %s) ON DUPLICATE KEY UPDATE username=%s"

更新

如果您想将 on duplicate key update 子句与批量插入一起使用(例如 executemany()),那么您不应在 中提供任何参数>update 子句,因为在批量插入语句中只能有一个更新子句。使用 values()代替函数:

query = "INSERT INTO pcf_dev_D.users(user_guid,username) " \
        "VALUES (%s, %s) ON DUPLICATE KEY UPDATE username=VALUES(username)"

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. 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. This function is especially useful in multiple-row inserts. The VALUES() function is meaningful only in the ON DUPLICATE KEY UPDATE clause or INSERT statements and returns NULL otherwise.

关于Python "INSERT INTO"与 "INSERT INTO...ON DUPLICATE KEY UPDATE",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255460/

相关文章:

php - 更改 PHP 版本后调用 Xampp 中未定义的函数 mb_detect_encoding() (PHPmyadmin)

python - 无限循环是不好的做法吗?

python 日期时间快速提取小时分钟

php - 尝试在我的 Controller 中获取非对象的属性

mysql - SQL中的Join语句

mysql - 根据 INFORMATION_SCHEMA 中的选择进行更新

sql - 需要SQL获取一条有两个对应条目的记录

python - 在 tensorflow 中读取大型数据集

c++ - 乘以二维矩阵。 用pycuda

python - 探索所有子序列