首页 > 解决方案 > sqlite SELECT 语句返回无

问题描述

从我的数据库查询返回字符串时遇到问题。第一步是创建一个数据库:

def create_database():

    # database setup
    try:
        con = sqlite3.connect('db/mydb.db')
        cur = con.cursor()
        cur.execute('CREATE TABLE IF NOT EXISTS user (id INTEGER NOT NULL PRIMARY KEY, balance REAL NOT NULL, text TEXT NOT NULL)')
        con.commit()
        con.close()
    except Error as e:
        print('Failed to setup database.\n' + e)
        exit(1)

def get_connection():

    try:
        con = sqlite3.connect('db/mydb.db')
        return con
    except:
        print('Unable to connect to database. Please try again later.\n')
        exit(1)

我的第二步是创建一个用户并将他添加INSERT到我的数据库中:

def create_user(user_id : int):

    balance = 0.0; # base unit = USD
    text = create_text()

    # connect to database
    con = get_connection()
    cur = con.cursor()

    cur.execute('INSERT INTO user (id, balance, text) VALUES (?, ?, ?)', (user_id, balance, text))

    database = cur.execute('SELECT * FROM user').fetchone()
    print(database)
    
    con.commit()
    con.close()

def create_text():

    # do some stuff which creates my text
    # the text is something like 'LNURL...'
    
    return text

这是我的数据库查询结果的样子:

(393120847059091456, 0.0, 'LNURL1DP68GURN8GHJ7URP09JX7MTPDCHXGEF0D3H82UNVWQHKZURF9AMRZTMVDE6HYMP0XGMQA9V7RT')

如果我尝试为我查询这个数据库,text它什么都不返回/ None。我的print(text)只是产生一个空的新行。

def get_text(user_id : int):

    # connect to database
    con = get_connection()
    cur = con.cursor()

    cur.execute('SELECT text FROM user WHERE id=?', (user_id,))
    text = cur.fetchone()

    con.commit()
    con.close()

    print(text)
    return text

标签: pythondatabasesqliteselectnonetype

解决方案


我认为我的 sqlite 数据库默认使用 32 位 int 值。因此,在创建表时强制它使用 64 位解决了我的问题:

cur.execute('CREATE TABLE IF NOT EXISTS user (id INT8 PRIMARY KEY NOT NULL, balance REAL NOT NULL, text TEXT NOT NULL')

比我可以用这个返回我的查询结果:return text[0]


推荐阅读