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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With