Py学习  »  Python

无法使用python从sqlite数据库获取数据

Julian Chu • 4 年前 • 1320 次点击  

我使用以下代码从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()中打印相同的东西。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/57197
 
1320 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Wonka
Reply   •   1 楼
Wonka    4 年前

self.conn.execute(command)
self.conn.commit() #<--- THIS NEW line, to after .execute()
self.table = table_name
Azzam Asghar
Reply   •   2 楼
Azzam Asghar    4 年前

results = cur.fetchall() :

for row in results:
    A = row[0]
    B = row[1]
Kostas Charitidis
Reply   •   3 楼
Kostas Charitidis    4 年前

它返回没有找到游标对象。 如果要获得结果,需要添加以下行:

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