3

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

1 Answer 1

3

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....")
Sign up to request clarification or add additional context in comments.

2 Comments

For additional safety, a uniqueness constraint on the DB would be a good idea.
I tried this #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' but didn't work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.