python - 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
解决方案
我认为我的 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]
推荐阅读
- jquery - 在 MVC 5 中,如何根据另一个下拉值删除所需的属性?
- android - 如果除非有修改的数据,否则firebase实时数据库不会触发数据获取,那么离线数据库如何工作?
- sql-server - VB.NET 数据表行
- regex - 使用正则表达式从不以注释符号开头的行中提取数字
- java - 访问/查找 HashMap 存储桶的时间复杂度是多少(不是存储桶中的值)?
- php - 在哪里插入 MySQl & PHP
- python - 使用python从文件中提取带有字符串的行
- spring-boot - Spring Boot 在 ServerOAuth2AuthorizedClientExchangeFilterFunction 中向 WebClient 请求添加附加属性
- javascript - 从多个 Apollo React 组件外部触发保存突变
- python - 蟒蛇和美丽的汤|| 在写入文件之前使用 Varible 进行正则表达式