mysql Flask-SQLAlchemy在创建表之前创建模式

5f0d552i  于 2023-03-17  发布在  Mysql
关注(0)|答案(2)|浏览(151)

我正在尝试使用Flask-SQLAlchemy配置MySQL模式。我有一个名为testdb的模式和一些表。我将列出一个表,User。到目前为止,此代码创建了所需的所有表,但仅当testdb已经存在时。是否有方法在连接之前检查并创建testdb

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/testdb'
db = SQLAlchemy(app)

class User(db.Model):
    userid = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(16), unique=True, nullable=False)
    password = db.Column(db.String(16), unique=False, nullable=False)
    email = db.Column(db.String(80), unique=True, nullable=False)
    createdDate = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    lastUpdated = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)

db.create_all()

所需命令:

CREATE SCHEMA IF NOT EXISTS `testdb` ;
bnlyeluc

bnlyeluc1#

我解决了这个感谢@hygorxaraujo看到下面的代码:

import sqlachemy

engine = sqlalchemy.create_engine('mysql://root:password@localhost') # connect to server
engine.execute("CREATE SCHEMA IF NOT EXISTS `testdb`;") #create db
engine.execute("USE testdb;") # select new db

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mypassword@localhost/testdb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #Turn off annoying message
db = SQLAlchemy(app)
bejyjqdl

bejyjqdl2#

下面是一种为模型上定义的所有模式自动执行此操作的方法:

class User(db.Model)
    __tablename__ = 'user'
    __table_args__ = { 'schema': 'user' }

    user_id = db.Column(db.BigInteger, primary_key=True)

def _create_all_schemas():
    # get all the tables defined in your models
    tables = db.Model.metadata.tables.values()

    # group the tables by schema
    schemas = {}
    for table in tables:
        schema_name = table.schema
        if schema_name not in schemas:
            schemas[schema_name] = []
        schemas[schema_name].append(table)

    # create the schemas
    with db.engine.connect() as conn:
        for schema_name, tables in schemas.items():
            if not conn.dialect.has_schema(conn, schema_name):
                conn.execute(sqlalchemy.schema.CreateSchema(schema_name))

        conn.commit()

# Sync
_create_all_schemas()
db.create_all()

相关问题