首页 > 解决方案 > 无法使用 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() 中打印相同的东西。

标签: pythonsqlite

解决方案


它返回没有找到游标对象。如果你想得到你需要添加这些行的结果:

cur = conn.cursor()  # create a cursor to your connection
cur.execute(your_query)  # execute your query
results = cur.fetchall()  # fetch the results

推荐阅读