Python | 解决 “OperationalError: (sqlite3.OperationalError) no such table: ...“ 问题

Python | 解决 “OperationalError: (sqlite3.OperationalError) no such table: …” 问题

问题发生环境:
操作系统:windows 10
python 3.7
flask 1.1.1
sqlite3为python3自带的库

具体情况:
下午在学习flaskr调用sqlite连接数据库的时候遇到了如下的报错信息:

sqlite3.OperationalError: no such table: entries

Traceback显示出错的语句是:

cur = g.db.execute('select title,text from entries order by id desc')

g.db对象的赋值语句如下:

DATABASE="flaskr.db"

g.db=connect_db()
def connect_db():
	return sqlite3.connect(DATABASE)

然而打开目录却发现在当前目录下存在连接的数据库文件,如图所示:
UTOOLS1586086312559.png

使用Navicat连接到flaskr.db文件也可以看到entries表是存在的
UTOOLS1586086449125.png

多番运用各类搜索引擎后后终于在stackoverflow上发现了有效的解决方案:

You are assuming that the current working directory is the same as the directory your script lives in. It is not an assumption you can make. Your script is opening a new database in a different directory, one that is empty.

Use an absolute path for your database file. You can base it on the absolute path of your script:

大意是说,脚本正在打开并尝试连接另一个目录中的新数据库,该目录是空的,因此找不到表。所以访问数据库文件时应该使用绝对路径而不是相对路径
在python脚本的合适位置加上如下代码,问题得到解决:

import os.path

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "flaskr.db")

更改后的连接数据库代码如下:

def connect_db():
	return sqlite3.connect(db_path)

特此记录下来,希望能对遇到同样问题的coder有帮助
如有帮助,欢迎点赞/转载~

联系邮箱:mrjingcheng@foxmail.com
有问题欢迎通过邮箱交流。

  • 19
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值