gpt4 book ai didi

Python:检查表中是否存在字段

转载 作者:可可西里 更新时间:2023-11-01 08:21:39 25 4
gpt4 key购买 nike

如何检查表中是否存在某个字段。我需要一个我认为可以做到这一点的 if 语句。

如果行中的字段包含相同数据,我不想将数据插入行中。

例如,我有一个包含 6 行的表格。前缀、code_id、answer、station_id、时间戳、comport。

用户通过控制台输入station_id和prefix,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:检查表中是否存在字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6549287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com