MySQLdb - Check if row exists Python

后端 未结 3 1069
借酒劲吻你
借酒劲吻你 2021-02-06 18:26

I am trying to check if a row exist with the same Name my database with python and can\'t quite get it here is what I am trying: (I know the connection is wokring)



        
3条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 19:11

    1. First of all you have a wrong syntax in your code. Python doesn't have a try...catch block. It has try...except block which is used like this:
    try:
        # something here
    except:
        # something here
    
    1. MySQL does not return an error when you use SELECT command. However there are two different ways you can find out if it returned something or not.

    PYTHON 2.7

    cursor.execute(
        "SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
        (item_name,)
    )
    # gets the number of rows affected by the command executed
    row_count = cursor.rowcount
    print "number of affected rows: {}".format(row_count)
    if row_count == 0:
        print "It Does Not Exist"
    

    PYTHON 3+

    cursor.execute(
        "SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
        (item_name,)
    )
    # gets the number of rows affected by the command executed
    row_count = cursor.rowcount
    print ("number of affected rows: {}".format(row_count))
    if row_count == 0:
        print ("It Does Not Exist")
    

    Another way to do this would be to fetch the statement and check if it is empty:

    # execute statement same as above  
    msg = cursor.fetchone()  
    # check if it is empty and print error
    if not msg:
        print 'It does not exist'
    

    This is my first answer, so I don't know how to style the code in the answer properly, it also seems messy because of that. Sorry for that.

    Also i use Python 3 and pymysql, so there may be some syntax error but I have tried to write the code according to python 2.7 from what I could remember about it.

    EDIT (5/1/2020)

    Thanks to @Arishta for pointing out that the first method will require you to fetch all rows before using row_count. i.e adding cursor.fetchall() before the row_count = cursor.rowcount

    cursor.execute(
        "SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
        (item_name,)
    )
    # Add THIS LINE
    results = cursor.fetchall()
    # gets the number of rows affected by the command executed
    row_count = cursor.rowcount
    print("number of affected rows: {}".format(row_count))
    if row_count == 0:
        print("It Does Not Exist")
    

    Use the cursor.fetchone() if you only care if the record exists or not.

提交回复
热议问题