How to check if record exists with Python MySQdb

后端 未结 4 1500
深忆病人
深忆病人 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:58

    I believe the most efficient "does it exist" query is just to do a count:

    sqlq = "SELECT COUNT(1) FROM settings WHERE status = '1'"
    xcnx.execute(sqlq)
    if xcnx.fetchone()[0]:
        # exists
    

    Instead of asking the database to perform any count operations on fields or rows, you are just asking it to return a 1 or 0 if the result produces any matches. This is much more efficient that returning actual records and counting the amount client side because it saves serialization and deserialization on both sides, and the data transfer.

    In [22]: c.execute("select count(1) from settings where status = 1")
    Out[22]: 1L  # rows
    
    In [23]: c.fetchone()[0]
    Out[23]: 1L  # count found a match
    
    In [24]: c.execute("select count(1) from settings where status = 2")
    Out[24]: 1L  # rows
    
    In [25]: c.fetchone()[0]
    Out[25]: 0L  # count did not find a match
    

    count(*) is going to be the same as count(1). In your case because you are creating a new table, it is going to show 1 result. If you have 10,000 matches it would be 10000. But all you care about in your test is whether it is NOT 0, so you can perform a bool truth test.

    Update

    Actually, it is even faster to just use the rowcount, and not even fetch results:

    In [15]: if c.execute("select (1) from settings where status = 1 limit 1"): 
                print True
    True
    
    In [16]: if c.execute("select (1) from settings where status = 10 limit 1"): 
                print True
    
    In [17]: 
    

    This is also how django's ORM does a queryObject.exists().

提交回复
热议问题