Python“INSERT INTO”与“INSERT INTO ... on DUPLICATE KEY UPDATE”

时间:2018-01-15 00:10:39

标签: python mysql

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

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更新记录就好......我错过了什么?

1 个答案:

答案 0 :(得分:0)

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

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)"
  

在ON DUPLICATE KEY UPDATE子句中的赋值表达式中,可以使用VALUES(col_name)函数来引用INSERT ... ON DUPLICATE KEY UPDATE语句的INSERT部分中的列值。换句话说,ON DUPLICATE KEY UPDATE子句中的VALUES(col_name)引用了将插入的col_name的值,没有发生重复键冲突。此功能在多行插入中特别有用。 VALUES()函数仅在ON DUPLICATE KEY UPDATE子句或INSERT语句中有意义,否则返回NULL。