Marc Brigham
Marc Brigham

Reputation: 2264

Python: Checking if field exists in table

How can I check if a field exists in a table. I need an if statement I believe to do this.

I don't want to insert data into the row if a field within the row contains the same data.

So for example I have a table with 6 rows. Prefix, code_id, answer, station_id, timestamp, comport.

The user will enter in the station_id through the console and the prefix,code_id, and answer all in one line. I split it up into three variables and store them in the database.

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))

But before this insert statement I want to see if the data the user enters is already in the table.

I hope I'm being clear enough. If not let me know and I will edit the question.

EDIT: I tried this with no luck

#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

Upvotes: 3

Views: 3385

Answers (1)

matt b
matt b

Reputation: 139931

If you want to see if there is data in the table already that meets the conditions, then you simply query for it:

In pseudo-code

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

Upvotes: 3

Related Questions