howto create db mysql with sqlalchemy

后端 未结 4 1284
别跟我提以往
别跟我提以往 2020-12-28 12:58

I need to create a db in mysql using sqlalchemy, I am able to connect to a db if it already exists, but I want to be able to create it if it does not exist. this are my tabl

相关标签:
4条回答
  • 2020-12-28 13:37

    I don't know what the canonical way is, but here's a way to check to see if a database exists by checking against the list of databases, and to create it if it doesn't exist.

    from sqlalchemy import create_engine
    
    # This engine just used to query for list of databases
    mysql_engine = create_engine('mysql://{0}:{1}@{2}:{3}'.format(user, pass, host, port))
    
    # Query for existing databases
    existing_databases = mysql_engine.execute("SHOW DATABASES;")
    # Results are a list of single item tuples, so unpack each tuple
    existing_databases = [d[0] for d in existing_databases]
    
    # Create database if not exists
    if database not in existing_databases:
        mysql_engine.execute("CREATE DATABASE {0}".format(database))
        print("Created database {0}".format(database))
    
    # Go ahead and use this engine
    db_engine = create_engine('mysql://{0}:{1}@{2}:{3}/{4}'.format(user, pass, host, port, db))
    

    Here's an alternative method if you don't need to know if the database was created or not.

    from sqlalchemy import create_engine
    
    # This engine just used to query for list of databases
    mysql_engine = create_engine('mysql://{0}:{1}@{2}:{3}'.format(user, pass, host, port))
    
    # Query for existing databases
    mysql_engine.execute("CREATE DATABASE IF NOT EXISTS {0} ".format(database))
    
    # Go ahead and use this engine
    db_engine = create_engine('mysql://{0}:{1}@{2}:{3}/{4}'.format(user, pass, host, port, db))
    
    0 讨论(0)
  • 2020-12-28 13:42

    You can use SQLAlchemy-Utils for that.

    pip install sqlalchemy-utils

    Then you can do things like

    from sqlalchemy_utils import create_database, database_exists
    url = 'mysql://{0}:{1}@{2}:{3}'.format(user, pass, host, port)
    if not database_exists(url):
        create_database(url)
    

    I found the answer here, it helped me a lot.

    0 讨论(0)
  • 2020-12-28 14:01
    CREATE DATABASE IF NOT EXISTS dbName;
    
    0 讨论(0)
  • 2020-12-28 14:02

    To create a mysql database you just connect to the server an create the database:

    import sqlalchemy
    engine = sqlalchemy.create_engine('mysql://user:password@server') # connect to server
    engine.execute("CREATE DATABASE dbname") #create db
    engine.execute("USE dbname") # select new db
    # use the new db
    # continue with your work...
    

    of course your user has to have the permission to create databases.

    0 讨论(0)
提交回复
热议问题