我有一个数据库,我想创建一个名为Employee的类,只给出empid并从数据库中获取其余部分。
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))
只有它不会返回值,而是在打印时返回一个对象。
<sqlite3.Cursor object at 0x104687c00> <sqlite3.Cursor object at 0x104687c00>
如何解决此问题?
答案 0 :(得分:1)
正确。执行查询后调用fetchone
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]
但实际上,这是更好的
cur.execute("SELECT name, bday FROM employees WHERE empid = ?", (empid,))
self,name, self.bday = cur.fetchone()
答案 1 :(得分:1)
您可以使用 fetchone()
来检索查询的第一个匹配项。这将通过索引(使用Row
检索第一个项目)返回[0]
对象,然后获取名称:
cursor = cur.execute("SELECT name FROM employees WHERE empid = " + str(empid))
self.name = cursor.fetchone()[0]
但话虽如此,以这种方式构建查询是危险的:它可能导致SQL injection。最好让execute
正确地转义查询:
cursor = cur.execute("SELECT name FROM employees WHERE empid = ?", (empid,))
self.name = cursor.fetchone()[0]
由于您同时获取两名员工的姓名和bday,您也可以在一个查询中执行此操作,然后将其解压缩:
cursor = cur.execute("SELECT name, bday FROM employees WHERE empid = ?", (empid,))
self.name, self.bday = cursor.fetchone()
建议使用ORM包(比如SQLAlchemy或Django)。