简体   繁体   English

如何使用 SQLAlchemy 在 PostgreSQL 中创建表?

[英]How do I create a table in PostgreSQL with SQLAlchemy?

I tried to create a table in the "app" database, but got this error:我试图在“app”数据库​​中创建一个表,但得到这个错误:

app=# CREATE TABLE users;
ERROR:  syntax error at or near ";"
LINE 1: LINE 1: CREATE TABLE users;
                                  ^

The columns are defined in models.py which is why I don't create them here.这些列是在models.py中定义的,这就是我不在这里创建它们的原因。

Do not create the tables in PostgreSQL, SQLAlchemy will create the table (and the columns) for you.不要在 PostgreSQL 中创建表,SQLAlchemy 会为你创建表(和列)。 All you need to do is create the database , which you have done.您需要做的就是创建数据库,您已经完成了。 To create the tables with Flask-SQLAlchemy:要使用 Flask-SQLAlchemy 创建表:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False, unique=True)

with app.app_context():
    db.create_all()

To address the error (although as stated above you should not do this), it is because that is not a full CREATE TABLE expression.为了解决这个错误(尽管如上所述你不应该这样做),这是因为那不是一个完整的CREATE TABLE表达式。 You need to specify zero or more columns for the table.您需要为表指定零个或多个列。

CREATE TABLE my_table ();

In my case forgot to import my Model class and code run without any error:).在我的情况下忘记导入我的模型类和代码运行没有任何错误:)。

If you call create_all() on interactive mode please ensure that you import particular Model class.如果您在交互模式下调用create_all()请确保您导入特定的模型类。

Note: Every time you make a change on Model class restart ipython.注意:每次对 Model 类进行更改时,都会重新启动 ipython。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM