How to check if record exists with Python MySQdb

后端 未结 4 1510
深忆病人
深忆病人 2021-02-14 05:25

Im creating a python program that connects to mysql.

i need to check if a table contains the number 1 to show that it has connected successfully, this is my code thus fa

4条回答
  •  遇见更好的自我
    2021-02-14 06:15

    When you run results = xcnx.fetchall(), the return value is a sequence of tuples that contain the row values. Therefore when you check if results == '1', you are trying to compare a sequence to a constant, which will return False. In your case, a single row of value 0 will be returned, so you could try this:

    results = xcnx.fetchall()
    # Get the value of the returned row, which will be 0 with a non-match
    if results[0][0]:
      print 'yep its connected'
    else:
      print 'nope not connected'
    

    You could alternatively use a DictCursor (when creating the cursor, use .cursor(MySQLdb.cursors.DictCursor) which would make things a bit easier to interpret codewise, but the result is the same:

    if results[0]['COUNT(*)]':
        # Continues...
    

    Also, not a big deal in this case, but you are comparing an integer value to a string. MySQL will do the type conversion, but you could use SELECT COUNT(*) FROM settings WHERE status = 1 and save a (very small) bit of processing.

提交回复
热议问题