Python SQlite返回一个Object而不是一个字符串

时间:2016-02-14 16:54:43

标签: python arrays sqlite

我正在尝试使用flask创建支持票证系统。我使用sqlite3作为我的票证数据库。我试图获得状态为“待定”的所有票据的“ID”,但是当我运行所述函数时它返回<sqlite3.Cursor object at 0x03746B20>是他们无论如何我可以将所有id作为字符串数组获取?

功能:

def GetPendingTickets():
  opendb()
  qry = "SELECT 'id' FROM 'tickets' WHERE 'Status'='Pending'"
  connection.row_factory = lambda cursor, row: row[0]
  openTickets = cursor.execute(qry)
  closedb()
  return openTickets

提前致谢!

2 个答案:

答案 0 :(得分:1)

您可以在执行后使用fetchallfetchonefetchmany

iIn [1]: import sqlite3

In [2]: con = sqlite3.connect(":memory:")

In [3]: cur = con.cursor()

In [4]: cur.executescript("""
   ...:     create table person(
   ...:         firstname,
   ...:         lastname,
   ...:         age
   ...:     );
   ...: 
   ...:     create table book(
   ...:         title,
   ...:         author,
   ...:         published
   ...:     );
   ...: 
   ...:     insert into book(title, author, published)
   ...:     values (
   ...:         'Dirk Gently''s Holistic Detective Agency',
   ...:         'Douglas Adams',
   ...:         1987
   ...:     );
   ...:     """)
Out[4]: <sqlite3.Cursor at 0x7f1eac026ce0>

In [5]: cur.execute("SELECT * FROM `book`")
Out[5]: <sqlite3.Cursor at 0x7f1eac026ce0>

In [6]: cur.fetchall()
[(u"Dirk Gently's Holistic Detective Agency", u'Douglas Adams', 1987)]

同时更改您的查询:

qry = "SELECT id FROM tickets WHERE Status = 'Pending'"

答案 1 :(得分:1)

删除引号会留下问题,为什么要这样做。

嗯,引用在SQL中有点笨拙。字符串文字用单引号引用,如'pending'(总是强制的),而字段和表名可以用"tickets"中的双引号引用,但这只是强制性的,当字段名称包含奇怪的时候字符或区分大小写。你正在大量使用字符串文字,但这不是你的意图。你可以写

qry = """SELECT "id" FROM "tickets" WHERE "Status" = 'Pending'"""

或者,最小化报价,写

qry = """SELECT id FROM tickets WHERE "Status" = 'Pending'"""

当状态字段的字段名称确实是“状态”而不是“状态”时(在这种情况下,您将创建带引号的表)。