sqlite3.OperationalError: no such table: users 问题解决!!

我已经100%创建了表格,而且db文件与app文件位于同一文件夹中,但在运行POST请求提交表单时,出现错误:

Traceback (most recent call last):
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\Anaconda3\envs\SafeHat\lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\PycharmProjects\Flask服务器\flask001.py", line 119, in user_login
    user = query_user_by_name(username)
  File "D:\PycharmProjects\Flask服务器\flask001.py", line 69, in query_user_by_name
    cur = g.db.execute(sql_select, args)
sqlite3.OperationalError: no such table: users

原因:

我可能正在使用数据库文件的相对路径,但却没有关注工作目录可能是什么,
我的脚本正在其他工作目录中打开一个新数据库,而这个目录下没有我的数据库db文件,也找不到我所创建的表

解决办法:

为数据库文件使用绝对路径。您可以基于脚本的绝对路径:

app = Flask(__name__)

app.config["DATABASE"] = 'database.db'#这里'database.db'为相对路径
def connect_db():
    """Connects to the specific database."""
    db = sqlite3.connect(app.config["DATABASE"])
    return db

改为

import os.path
app = Flask(__name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "database.db")
app.config["DATABASE"] = db_path#这里db_path为绝对路径
def connect_db():
    """Connects to the specific database."""
    db = sqlite3.connect(app.config["DATABASE"])
    return db

改为绝对路径后,无论你的工作目录是什么,都可以通过绝对路径访问到数据库,问题就解决了。
参考文章:Python sqlite3.OperationalError: no such table

你可能感兴趣的:(python学习)