如何检查表中是否存在字段.我需要一个if语句,我相信可以这样做.
如果行中的字段包含相同的数据,我不想在行中插入数据.
例如,我有一个包含6行的表.前缀,code_id,答案,station_id,时间戳,comport.
用户将通过控制台输入station_id和前缀code_id,并在一行中全部回答.我将其分为三个变量,并将其存储在数据库中.
cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station_id,timestamp,comport) VALUES(%s, %s, %s, %s, %s, %s)""",(prefix, code_id, answer, station, timestamp,station))
但是在此插入语句之前,我想查看用户输入的数据是否已在表中.
我希望我已经足够清楚了.如果没有,请告诉我,我将编辑问题.
编辑:我没有运气尝试过
#test if fields exist before inserting!
query = cursor.execute("""SELECT count(*) FROM scan WHERE prefix = %s and code_id = %s and answer = %s and station_id = %s""",
(prefix, code_id, answer, station,))
if query != 1:
cursor.execute("""INSERT INTO scan (prefix, code_id, answer, station_id,timestamp,comport) VALUES(%s, %s, %s, %s, %s, %s)""",
(prefix, code_id, answer, station, timestamp,station))
print 'Thank you for checking into station: ', station ,'please wait for the beep
解决方法:
如果要查看表中是否已经有满足条件的数据,则只需查询一下即可:
用伪代码
if "select count(*) from scan where prefix = ? and code_id = ? and ..." == 0:
execute("insert into scan....")
标签:python,mysql