Python Class SQLite3 request returns object

*爱你&永不变心* 提交于 2021-01-28 09:09:13

问题


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?


回答1:


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).




回答2:


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()


来源:https://stackoverflow.com/questions/48126592/python-class-sqlite3-request-returns-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!