繁体   English   中英

更新sql行使用Python在数据库中添加新行

[英]Updating sql row adds new row in DB using Python

我正在尝试更新MySQL数据库中的特定行,但不是在数据库中添加新行。我正在使用localhost连接到db。有人可以告诉我我要去哪里吗?

我的代码:

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

我得到以下输出:

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

cursor.fetchall()返回一个元组列表,因此您只在查找id(整数),而不是元组,并且条件始终为False,从而导致您的代码始终插入新记录。 要使其工作,请在查找元素时尝试以下方法:

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

希望能帮助到你,

暂无
暂无

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

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