Flask 数据库初始化时语法错误

0 投票
1 回答
607 浏览
提问于 2025-04-18 07:15

如果有人看到我之前的问题,我已经解决了那个问题,但在同一个函数里又出现了一个新问题,我搞不懂。

这个函数在我看来语法上是正确的:

def init_db():
    """Initializes the database."""
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()

但是我遇到了这个错误:

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-2-ad60ea155641> in <module>()
----> 1 init_db()

/Users/andrew/code/pos_system/routes.py in init_db()
     31         db = get_db()
     32         with app.open_resource('schema.sql', mode='r') as f:
---> 33             db.cursor().executescript(f.read())
     34         db.commit()
     35

OperationalError: near ")": syntax error

我在第33行的括号上没有发现任何错误……

1 个回答

0

这是来自@alecxe在评论中的回答:

错误并不是出在python代码里,而是在schema.sql文件里面。你可以通过异常类型来判断,因为它是OperationalError(这不是python自带的错误类型),而不是SyntaxError

撰写回答