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

3 投票
1 回答
3346 浏览
提问于 2025-04-16 20:40

我想知道怎么检查一个表里是否有某个字段。为了做到这一点,我觉得需要用到一个if语句。

我不想在某一行插入数据,如果这一行里的某个字段已经有相同的数据。

举个例子,我有一个表,里面有6行数据,分别是前缀(prefix)、代码ID(code_id)、答案(answer)、站点ID(station_id)、时间戳(timestamp)和端口(comport)。

用户会通过控制台输入站点ID,然后把前缀、代码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

1 个回答

3

如果你想查看表格里是否已经有符合条件的数据,那你只需要查询一下就可以了:

用伪代码表示如下:

if "select count(*) from scan where prefix = ? and code_id = ? and ..." == 0:
    execute("insert into scan....")

撰写回答