我有一個問題,從我的資料庫查詢回傳一個字串。第一步是創建一個資料庫:
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
uj5u.com熱心網友回復:
我認為我的 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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341407.html
