How to check if record exists with Python MySQdb

后端 未结 4 1574
深忆病人
深忆病人 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 05:59

    If all you want to do is check if you have successfully established a connection then why are you trying to create a table, insert a row, and then retrieve data from it?

    You could simply do the following...

    sqlq = "SELECT * FROM settings WHERE status = '1'"
    xcnx.execute(sqlq)
    results = xcnx.fetchone()
    if results =='1':
      print 'yep its connected'
    else:
      print 'nope not connected'
    

    In fact if your program has not thrown an exception so far indicates that you have established the connection successfully. (Do check the code above, I'm not sure if fetchone will return a tuple, string, or int in this case).

    By the way, if for some reason you do need to create the table, I would suggest dropping it before you exit so that your program runs successfully the second time.

提交回复
热议问题