How to create a new database using SQLAlchemy?

前端 未结 4 1583
余生分开走
余生分开走 2020-11-28 19:34

Using SQLAlchemy, an Engine object is created like this:

from sqlalchemy import create_engine
engine = create_engine(\"postgresql://localhost/mydb\")
         


        
4条回答
  •  再見小時候
    2020-11-28 20:13

    Please note that I couldn't get the above suggestions with database_exists because whenever I check if the database exists using if not database_exists(engine.url): I get this error:

    InterfaceError('(pyodbc.InterfaceError) (\'28000\', u\'[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user \\'myUser\\'. (18456) (SQLDriverConnect); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "MY_DATABASE" requested by the login. The login failed. (4060); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user \\'myUser\\'. (18456); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot open database "MY_DATABASE" requested by the login. The login failed. (4060)\')',)

    Also contextlib/suppress was not working and I'm not using postgres so I ended up doing this to ignore the exception if the database happens to already exist with SQL Server:

    import logging
    import sqlalchemy
    
    logging.basicConfig(filename='app.log', format='%(asctime)s-%(levelname)s-%(message)s', level=logging.DEBUG)
    engine = create_engine('mssql+pyodbc://myUser:mypwd@localhost:1234/MY_DATABASE?driver=SQL+Server+Native+Client+11.0?trusted_connection=yes', isolation_level = "AUTOCOMMIT")
    
    try: 
        engine.execute('CREATE DATABASE ' + a_database_name)
    except Exception as db_exc:
        logging.exception("Exception creating database: " + str(db_exc))  
    

提交回复
热议问题