Have a program that recieves a list of player names and results. Then trys to add them to a 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. 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. 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:
Player
(or better yet, it is the primary key). Score
to be NOT NULL
to ensure that it always has reasonable values. sql_insert_query = " INSERT INTO results (Player, Score) VALUES {0},{1}) ON DUPLICATE
KEY UPDATE Score = VALUES(Score) + {1}; ".format(playerNames[0],playerScore[1])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.