【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")

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

扫描二维码关注公众号,回复: 11298265 查看本文章
def connect_db():
	return sqlite3.connect(db_path)

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

联系邮箱:[email protected]
有问题欢迎通过邮箱交流。

猜你喜欢

转载自blog.csdn.net/weixin_43207777/article/details/105332134