制作" SELECT"查询我的SQLite3数据库我发现做一些简单的操作非常麻烦,只需要进入数据库并获取一个值,并使其看起来与我在程序中完全一样,就像在db中一样。我不熟悉,不知道这是不是就是这样,或者是否有更好的方法来做这些事情。
这个问题的第一个要素是关于这样的事实:
player_name = c.execute("""SELECT name FROM players WHERE pid = ?""", (pid,))
print(player_name)
会产生这样的结果:
<sqlite3.Cursor object at 0x10c185110>
我发现提取实际内容的唯一方法是迭代生成的游标并将内容存储在列表中:
player_name = []
sql = c.execute("""SELECT name FROM players WHERE pid = ?""", (pid,))
for result in sql:
player_name.append(result)
player_name = str(player_name).replace("[", "").replace("]", "")
另一个因素不是问题,但我想我会把它扔出去。事实上,上面例子中的每个结果看起来都像这样:
>>> print(player_name)
('Ben Johnson',)
最后,为了从数据库中获取确切的字符串并进入我的程序,我为每个查询执行此操作:
>>> player_name = []
>>> sql = c.execute("""SELECT name FROM players WHERE pid = ?""", (pid,))
>>> for result in sql:
>>> player_name.append(result)
>>> player_name = str(player_name).replace("[", "").replace("]", "")
>>> player_name = str(player_name).replace("('", "").replace("',)", "")
>>>
>>> print(player_name)
Ben Johnson
答案 0 :(得分:0)
execute
返回的游标对象包含行列表(实际上,它们是按需计算的);你应该用for
或类似的东西迭代光标。
每一行都是一个包含所有列值的元组。要获得第一列,只需执行row[0]
:
for row in c.execute("SELECT SomeColumn FROM ..."):
print(row[0])
如果要从单行获取单个列值,可以编写辅助函数:
def query_single_value(db, query, *parameters):
cursor = db.execute(query, parameters)
for row in cursor:
return row[0]
else:
return None # not found
print(query_single_value(c, "SELECT name FROM players WHERE pid = ?", pid))