Krisso123
Krisso123

Reputation: 175

Check Python SQL Query result for variable

I'm new to Python and working with SQL queries. I have a database that contains a table with meetings and their date along with an ID. What I want to do is check what meetings are happening on today's date. The code below results in showing all the meeting ID's that are happening on todays date. However I then want to check if a certain meeting ID is in the results, which I have stored as a variable, and if it is in there to carry out an IF function so I can then elaborate.

cur.execute("SELECT id FROM meeting WHERE DATE(starttime) = DATE(NOW())")

for row in cur.fetchall() :
    print row[0]

Upvotes: 4

Views: 3546

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121366

You can ask the database to tell you if the id is there:

cur.execute("SELECT id FROM meeting WHERE DATE(starttime) = DATE(NOW()) AND id=%s", (id,))
if cur.rowcount:
    # The id is there
else:
    # The id is not there.

I am assuming that you are using MySQLdb here; different database adapters use slightly different query parameter styles. Others might use ? instead of %s.

Upvotes: 4

Related Questions