sqlite SELECT 语句 returns None

sqlite SELECT statement returns None

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

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 查询此数据库,它 returns 没有/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

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

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

我可以 return 我的查询结果:return text[0]