python - 无法使用 python 从 sqlite 数据库中获取数据
问题描述
我使用以下代码从 sqlite3 数据库中获取项目
def get(self, item_name, attrs=True): #get attr from item and return as dict, if attr==True: get all items
conn = self.conn
if attrs: #all
return conn.execute('SELECT * FROM %s WHERE __item_key__ = "%s";' %(self.table, item_name))
else:
command = 'SELECT '
for attr in attrs:
command+= attr+' '
command+='FROM %s WHERE __item_key__ = "%s";' %(self.table, item_name)
return conn.execute(command)
print(get('name1'))
代码打印以下内容:
<sqlite3.Cursor at 0x213d4c0f490>
而不是表中的值。
当我尝试这个时:
get('name1')[0]
它返回:
TypeError: 'sqlite3.Cursor' object is not subscriptable
完整代码:
import sqlite3 as sql
import sqlite3 as sql
class db:
'''
This class turns dicts into sqlite databases
and output sqlite databases as dicts
'''
def __init__(self, db_name, table_name): #open or create a database
conn = sql.connect(db_name).cursor()
self.table = table_name
self.conn = conn
def create(self, table_name, cols):
command = "CREATE TABLE %s(_item_key_ TEXT," % table_name
for key, value in cols.items():
command+="%s %s," %(key, value)
command=command[:-1]
command+=");"
self.conn.execute(command)
self.table = table_name
def get(self, item_name, attrs=True): #get attr from item and return as dict, if attr==True: get all items
conn = self.conn
if attrs: #all
return conn.execute('SELECT * FROM %s WHERE _item_key_ = "%s";' %(self.table, item_name))
else:
command = 'SELECT '
for attr in attrs:
if type(attr) == str:
attr = '"'+attr+'"'
command+= str(attr)+' '
command+='FROM %s WHERE _item_key_ = "%s";' %(self.table, item_name)
return conn.execute(command).fetchall()
def change(self, item_name, attrs): #change certain attrs of item
command = 'UPDATE %s SET ' %self.table
for key, value in attrs:
command += '%s=%s,'%(key, value)
command = command[:-1]+' WHERE _item_name_ = "'+item_name+'";'
def add(self, item_name, attrs): #add an item with attrs to database
command = 'INSERT INTO %s VALUES ("%s",' %(self.table, item_name)
for attr in attrs:
if type(attr) == str:
attr = '"'+attr+'"'
command += str(attr)+','
command = command[:-1]+');'
#print(command)
self.conn.execute(command)
def close(self): #close database
self.conn.close()
该表应该如下所示(尽管我从未见过):
__item_name__ A B
---------------------------
'name1' 123 'hi'
'name2' 344 'bye'
有谁知道这是如何工作的?
编辑:我意识到 create() 和 add() 中的一些错误。但是,在修复了一些东西之后,它仍然在 get() 中打印相同的东西。
解决方案
它返回没有找到游标对象。如果你想得到你需要添加这些行的结果:
cur = conn.cursor() # create a cursor to your connection
cur.execute(your_query) # execute your query
results = cur.fetchall() # fetch the results
推荐阅读
- amazon-web-services - 在哪里阅读 AWS DLM(数据生命周期管理)错误详细信息
- javascript - 循环遍历 Javascript 中的函数
- mongodb - 在底层 C 驱动程序中执行许多插入和捕获异常时,mongocxx 崩溃
- r - 通过从另一个表中查找值来更新列值
- javascript - 应用引导程序后具有透视图的元素上不需要的阴影边框
- algorithm - 为什么平衡 BST 在可变结构中的二进制堆上没有普遍使用?
- javascript - 反应不渲染地图功能
- python - Reddit bot 仅在运行时获取新帖子,但不会主动获取在 bot 已经运行时发布的帖子
- c# - C# 任务调用相同的实例
- wordpress - 尝试了一切,但 wp-admin 仍然显示空白屏幕