stockton
Posts: 76
Joined: Mon Aug 24, 2015 6:06 am

extract variables from mariadb select

Sat Jul 14, 2018 4:55 am

Please help me fix the following program.

Code: Select all

#!/usr/bin/python
import mysql.connector as mariadb

mariadb_connection = mariadb.connect(user='root', password='123456789', database='gae3')
cursor = mariadb_connection.cursor()

#retrieving information
Name = " "
cellNumber  = " "
email = " "
notes = " "
cursor.execute("SELECT id, Name, cellNumber, email, notes FROM members where id=1463")
Name = cursor.fetchone()[0]
cellNumber = cursor.fetchone()[1]
email = cursor.fetchone()[2]
notes = cursor.fetchone()[3]
print("{0} {1} {2} {3}".format(Name,cellNumber,email,notes))
mariadb_connection.close()
Which when run tells me:-

Code: Select all

[email protected]:~/Develop/python $ python3 index.py
Traceback (most recent call last):
  File "index.py", line 14, in <module>
    cellNumber = cursor.fetchone()[1]
TypeError: 'NoneType' object is not subscriptable
[email protected]:~/Develop/python $

User avatar
rpdom
Posts: 12660
Joined: Sun May 06, 2012 5:17 am
Location: Ankh-Morpork

Re: extract variables from mariadb select

Sat Jul 14, 2018 6:56 am

Every time you use "cursor.fetchone()" it tries to read the next returned row from the query. Your query is only returning one row. The "Name = cursor.fetchone()[0]" line will read that result and extract the first element of it. The line "cellNumber = cursor.fetchone()[1]" will try and read another row, but there isn't one to read.

Try this which fetches the row once

Code: Select all

Result = cursor.fetchone()
Name = Result[0]
cellNumber = Result[1]
email = Result[2]
notes = Result[3]

stockton
Posts: 76
Joined: Mon Aug 24, 2015 6:06 am

Re: extract variables from mariadb select

Sat Jul 14, 2018 7:36 am

Thank you that worked for me.

Return to “Python”

Who is online

Users browsing this forum: No registered users and 10 guests