简体   繁体   中英

Updating sql row adds new row in DB using Python

i am trying to update a particular row in MySQL DB,but instead of that it's adding new row in the DB.I am using localhost to connect to db.Could anyone tell me where i am going wrong?

My Code:

import ConfigParser
import MySQLdb
from time import strftime

global TEST_RUN_STATUS                    
#Open database connection

config = ConfigParser.ConfigParser()
config.read('DB.cfg')
host=config.get("mySQL_id1", "localhost")
user= config.get("mySQL_id1", "username")
passwd= config.get("mySQL_id1", "password")
db= config.get("mySQL_id1", "DB_name")

### Connecting To DB                                                      
db_connect = MySQLdb.connect(host, user, passwd, db)                                            
cursor = db_connect.cursor()


TEST_ID=302
TIMESTAMP=strftime("%Y-%m-%d %H:%M:%S")
print TIMESTAMP


TestIDList=cursor.execute('''select TEST_ID from TEST_RESULTS''')
TestIDList=cursor.fetchall()


if TEST_ID in TestIDList:  
    cursor.execute('''UPDATE TEST_RESULTS SET TIMESTAMP = %s where TEST_ID=%s''',(TIMESTAMP,TEST_ID))
    db_connect.commit()
else:

    cursor.execute('''INSERT into TEST_RESULTS(TEST_ID,TIMESTAMP)values (%s, %s)''',(TEST_ID,TIMESTAMP))
    db_connect.commit()

I am getting the following output:

TEST_ID     TIMESTAMP
302        2015-01-10 19:06:03
302        2015-01-10  19:06:21

cursor.fetchall() returns a list of tuples, so you are looking only for the id (int number), instead of a tuple and the condition always evaluates to False, causing your code to insert a new record always. To make it work, just try this approach instead when looking for the element:

#Code before
#Just looking for a tuple instead of an int on the IDs list
if (TEST_ID,) in TestIDList:  
    #Rest of your code

Hope it helps,

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.

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