sqlalchemy, setting MySQL charset as `create_engine` argument

后端 未结 2 1203
青春惊慌失措
青春惊慌失措 2021-01-21 00:10

I create sqlalchemy engine connecting to MySQL database. I want to specify charset as create_engine argument.

If I use create_engine

相关标签:
2条回答
  • 2021-01-21 00:48

    the additional DBAPI arguments, when passed separately, are passed via connect_args.

    0 讨论(0)
  • 2021-01-21 00:49

    You can use sqlalchemy.engine.url.URL class

    import os
    from sqlalchemy import create_engine
    from sqlalchemy.engine.url import URL
    
    DB = {
        'drivername': 'mysql',
        'host': '127.0.0.1',
        'port': '3306',
        'username': os.environ['DBUNAME'],
        'password': os.environ['DBPASS'],
        'database': os.environ['DBNAME']
    }
    
    engine = create_engine(URL(**DB), connect_args={'charset':'utf8'})
    

    Or even better

    DB = {
        'drivername': 'mysql',
        'host': '127.0.0.1',
        'port': '3306',
        'username': os.environ['DBUNAME'],
        'password': os.environ['DBPASS'],
        'database': os.environ['DBNAME'],
        'query': {'charset':'utf8'}
    }
    
    engine = create_engine(URL(**DB))
    

    According to the docs URL class has the following parameters

    • drivername – the name of the database backend. This name will correspond to a module in sqlalchemy/databases or a third party plug-in.
    • username – The user name.
    • password – database password.
    • host – The name of the host.
    • port – The port number.
    • database – The database name.
    • query – A dictionary of options to be passed to the dialect and/or the DBAPI upon connect.
    0 讨论(0)
提交回复
热议问题