简体   繁体   中英

Python MySQL Connector Printing Results

I'm trying to retrieve data from a mysql server using the Python MySQL Connector.

So far, I have the query set up right using example code I found, and other resources. The problem is, I'm not sure how get it to print back all the rows, instead of just a certain row.

The code I'm using is:

def dbConnect(tag):
    qrfid = tag
    cnx = mysql.connector.connect(user='root', password='root', host='localhost', database='test')
    cursor = cnx.cursor(buffered=True)

    query = ("SELECT * FROM `user` WHERE `rfid`= %s")


    cursor.execute(query, (qrfid,))

    if not cursor.rowcount:
        print("No results found")
    else:
        for row in cursor:
            print row[1]

    cursor.close()
    cnx.close()

I'm using a test table that has only 3 columns in it: id, name, and rfid.

The above code only prints out the 2nd column, name, where if I put row[0], I get id, etc.

I'm use to using PHP for queries, but the RFID readers I'm using only have Python, Flash, and C support. Python is the language I know the most out of those 3.

Thanks!

Morning Trevor,

it is a bit late, but your question seems to be unanswered and should not stay like this.

I guess you've mistaken the way the data is returned. You assumed that you access the data of the header using row[0] and the records using row[1], row[2] ... But actually, the "for row in cursor:" statement creates an iterator for the cursor object, which returns one complete record per loop. The record is represented in form of a tuple, referenced by name row. You can display the while record using "print(record)" or slice out the first column with row[0], second with row[1], etc.

So, everything seems fine. However, be careful with the query where clause. When comparing to a string (%s placeholder), you should always enclose the string in quotes. Some SQL interpreters expect string literals in comparisons to be quoted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM