Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining when no database rows match with Python mysql.connector

I'm building a new Python 3 interface to an existing mySQL database. The table called "Tickets" may or may not contain a row for a particular member. I'm trying to fetch the ticket number if it exists, and do something else if it doesn't. My code looks like this:

import mysql.connector

config = {
  'user': 'XXXXXXXXXXXXX',
  'password': 'XXXXXXXXXXXXX',
  'host': 'XXXXXXXXXXXXX',
  'database': 'XXXXXXXXXXXXX',
  'raise_on_warnings': True
}

membernum = 9

db = mysql.connector.connect(**config)
if db.is_connected():
    cursor = db.cursor()
    query = "SELECT ticketnum FROM Tickets WHERE membernum={} limit 1".format(membernum)
    cursor.execute(query)
    if cursor.rowcount == 0:
        print("No results")
    else:
        result = cursor.fetchone()
        ticketnum = result[0]
        print(ticketnum)
    cursor.close
    db.close
else:
    print("Connection error")

It works beautifully if there is a record matching that member. If not, it generates:

Traceback (most recent call last):
  File "/Users/Gary/IPPS/samplecode.py", line 22, in <module>
    ticketnum = result[0]
TypeError: 'NoneType' object is not subscriptable

What am I doing wrong?

UPDATE

The answer from murphy1310 took care of it! I changed the code to the following, and it worked just fine:

import mysql.connector

config = {
  'user': 'XXXXXXXXXXXXX',
  'password': 'XXXXXXXXXXXXX',
  'host': 'XXXXXXXXXXXXX',
  'database': 'XXXXXXXXXXXXX',
  'raise_on_warnings': True
}

membernum = 9

db = mysql.connector.connect(**config)
if db.is_connected():
    cursor = db.cursor()
    query = "SELECT ticketnum FROM Tickets WHERE membernum={} limit 1".format(membernum)
    cursor.execute(query)
    result = cursor.fetchone()
    if result != None:
        ticketnum = result[0]
        print(ticketnum)
    else:
        print("No results")
    cursor.close
    db.close
else:
    print("Connection error")
like image 324
Gary R. Avatar asked Jun 17 '26 05:06

Gary R.


1 Answers

When no records match the search, cursor.fetchone() throws out a None.
So, your 'result' is None.
Hence the error when you try to dig deeper into the 'result' by using result[0].
It's best you place null checks.

like image 96
murphy1310 Avatar answered Jun 18 '26 18:06

murphy1310



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!