简体   繁体   中英

Flask-SQLAlchemy creating schema before creating tables

I am trying to configure a MySQL schema using Flask-SQLAlchemy. I have a schema called testdb and some tables. I will list one table, User . This code, so far, creates all of the tables needed but only when testdb already exists. Is there a way to check and create testdb before I connect?

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()

Desired command:

CREATE SCHEMA IF NOT EXISTS `testdb` ;

I solved this thanks to @hygorxaraujo See the code below:

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:8milerun@localhost/testdb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #Turn off annoying message
db = SQLAlchemy(app)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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