Python, mysql.connector Error: No Result Set to Fetch From; cgitb shows correct value being passed to function

前端 未结 2 952
眼角桃花
眼角桃花 2021-01-22 07:53

Allright this one\'s got me baffled so I decided to see if I could find a response on here, I\'ve searched up and down and several stackoverflow questions and answers and nothin

相关标签:
2条回答
  • 2021-01-22 08:12

    As clockwatcher said, you called cursor.fetchall() twice, and his solution to fix it would solve the problem.

    The way your SQL query itself is written leaves your code open to serious security vulnerabilities, since the query wouldn't escape the input parameters correctly. Similar to clockwatcher's response, a correct SQL query could be:

    query = ("SELECT * FROM sessionkeys WHERE clientName='%s'", (value1,))
    

    Also, since you aren't modifying any data, according to the mySQL connector documentation, there is no need to call the commit() method.

    As such, incorporating all three changes, your code would look something like:

    def session_fetch(value1):
        cnx = mysql.connector.connect(user='xxx', password='xxx', 
        host='127.0.0.1', database='xxx') 
        cursor = cnx.cursor()
        query = ("SELECT * FROM `sessionkeys` WHERE `clientName`='%s'", (value1,))
        cursor.execute(query)
        rows = cursor.fetchall()
        results = len(rows) 
        if results > 0:
            row = rows[0]
            clientName, clientAddr, unLocker = row[1], row[2], row[3]
        cursor.close()
        cnx.close()
    
    0 讨论(0)
  • 2021-01-22 08:16

    You're calling cursor.fetchall() twice. You shouldn't be doing that.

    Change:

    row = cursor.fetchall()
    results = len(cursor.fetchall())
    clientName, clientAddr, unLocker = row[1], row[2], row[3]
    

    To:

    rows = cursor.fetchall()
    results = len(rows) 
    if results > 0:
        row = rows[0]
        clientName, clientAddr, unLocker = row[1], row[2], row[3]
    

    And while it doesn't have anything to do with your current problem, you should be using a parameterized query:

    query = "SELECT * FROM sessionkeys WHERE clientName=?" 
    cursor.execute(query, (value1,))
    
    0 讨论(0)
提交回复
热议问题