python怎么判断字段不存在_Python:检查表中是否存在字段

如何检查表中是否存在字段.我需要一个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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值