简体   繁体   English

Python更新SQL DB

[英]Python updating a sql DB

Have a program that recieves a list of player names and results. 有一个程序可以接收播放器名称和结果的列表。 Then trys to add them to a SQL DB. 然后尝试将它们添加到SQL DB。 If the player name is already on the list I want it to update there Score by adding there current score to the stored one. 如果玩家名称已经在列表中,我希望它通过将当前分数添加到已存储的分数来在该分数处更新分数。 I'm trying to do this by using the ON DUPLICATE KEY UPDATE statement but I'm unsure how to tell it to use the value. 我正在尝试通过使用ON DUPLICATE KEY UPDATE语句来执行此操作,但是我不确定如何告诉它使用该值。 Here is my code. 这是我的代码。

from mysql.connector.cursor import MySQLCursorPrepared
print(playerNames ,playerScore )
try:
    #MariaDB Connection
    con = mysql.connector.connect(port=5004,user='root',password='password',host='localhost',database='scoreboard')
    records_to_insert = [ (playerNames[0],playerScore[0]) ,
                        (playerNames[1],playerScore[1]),
                        (playerNames[2],playerScore[2]) ,
                        (playerNames[3],playerScore[3]) 
                        ]
    sql_insert_query = " INSERT INTO results (Player, Score) VALUES (%s,%s) ON DUPLICATE KEY UPDATE Score = VALUES(Score) + %s; "
    myCursor = con.cursor()
    myCursor.executemany(sql_insert_query, records_to_insert)

    con.commit()

I know the issue is with using "= VALUES(Score) + %s" but I'm not sure of how else to tell it what value I want to use there. 我知道问题出在使用“ = VALUES(Score)+%s”,但是我不确定如何再告诉它我要在此处使用什么值。 Any advice would be greatly appreciated. 任何建议将不胜感激。

You can simply use this expression: 您可以简单地使用以下表达式:

INSERT INTO results (Player, Score)
    VALUES (%s, %s)
    ON DUPLICATE KEY UPDATE Score = VALUES(Score) + Score;

Notes: 笔记:

  • This assumes that you have a unique index on Player (or better yet, it is the primary key). 假设您在Player上具有唯一索引(或者更好的是,它是主键)。
  • You should learn to use SQL parameters for passing in values, rather than string substitution. 您应该学习使用SQL参数来传递值,而不是字符串替换。
  • You might want to declare Score to be NOT NULL to ensure that it always has reasonable values. 您可能需要将Score声明为NOT NULL以确保其始终具有合理的值。
 sql_insert_query = " INSERT INTO results (Player, Score) VALUES {0},{1}) ON DUPLICATE 
 KEY UPDATE Score = VALUES(Score) + {1}; ".format(playerNames[0],playerScore[1])

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

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