我正在尝试更新MySQL数据库中的特定行,但不是这样,它在DB中添加新行。我使用localhost连接到db.Could有人告诉我哪里出错了?
我的代码:
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
答案 0 :(得分:0)
cursor.fetchall()返回一个元组列表,因此您只查找id(int number)而不是元组,并且条件始终计算为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
希望它有所帮助,