DJDiaper
DJDiaper

Reputation: 11

Python Class SQLite3 request returns object

I have a database where I want to make a class called Employee, giving only the empid and getting the rest from a database.

    def__init__(self, empid):
    conn = sqlite3.connect("employee.db")
    cur = conn.cursor()
    self.empid = empid
    self.name = cur.execute("SELECT name FROM employees WHERE empid = " + str(empid))
    self.bday = cur.execute("SELECT bday FROM employees WHERE empid = " + str(empid))

Only it does not return the values, rather an object when I print it.

<sqlite3.Cursor object at 0x104687c00> <sqlite3.Cursor object at 0x104687c00>

How do I resolve this?

Upvotes: 1

Views: 1390

Answers (2)

Ursus
Ursus

Reputation: 30071

Correct. Call fetchone after execute the query

cur.execute("SELECT name FROM employees WHERE empid = ?", (empid,))
self.name = cur.fetchone()[0]
cur.execute("SELECT bday FROM employees WHERE empid = ?",(empid,))
self.bday = cur.fetchone()[0]

but actuallly, this is better

cur.execute("SELECT name, bday FROM employees WHERE empid = ?", (empid,))
self,name, self.bday = cur.fetchone()

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477641

You can use fetchone() to retrieve the first match of the query. This will return a Row object, by indexing (retrieving the first item with [0]), you then get the name so:

cursor = cur.execute("SELECT name FROM employees WHERE empid = " + str(empid))
self.name = cursor.fetchone()[0]

But that being said, constructing queries such way is dangerous: it can result in SQL injection. You better let execute escape the query properly:

cursor = cur.execute("SELECT name FROM employees WHERE empid = ?", (empid,))
self.name = cursor.fetchone()[0]

Since you fetch the name and bday of the two employees at the same time, you can also do this in one query, and then unpack it:

cursor = cur.execute("SELECT name, bday FROM employees WHERE empid = ?", (empid,))
self.name, self.bday = cursor.fetchone()

and it is advisable to use an ORM package (like SQLAlchemy or Django instead).

Upvotes: 1

Related Questions