Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get sqlalchemy.create_engine with mysqlconnector to connect using mysql_native_password?

I'm working with pandas and sqlalchemy, and would like to load a DataFrame into a MySQL database. I'm currently using this code snippet:

db_connection = sqlalchemy.create_engine('mysql+mysqlconnector://user:pwd@hostname/db_name')

some_data_ref.to_sql(con=db_connection, name='db_table_name', if_exists='replace')

sqlalchemy, pandas have been imported prior to this.

My MySQL backend is 8.x, which I know uses caching_sha2_password. If I were to connect to the database using mysql.connector.connect and I want to use the mysql_native_password method, I know that I should specify auth_plugin = mysql_native_password like so:

mysql.connector.connect(user=user, password=pw, host=host, database=db, auth_plugin='mysql_native_password')

My question: Is there a way to force mysql_native_password authentication with sqlalchemy.create_engine('mysql+mysqlconnector://...)?

Any advice on this would be much appreciated...

like image 443
baffledpopcorn Avatar asked Dec 17 '22 21:12

baffledpopcorn


1 Answers

You could use connect_args:

db_connection = sqlalchemy.create_engine(
    'mysql+mysqlconnector://user:pwd@hostname/db_name',
    connect_args={'auth_plugin': 'mysql_native_password'})

or the URL query:

db_connection = sqlalchemy.create_engine(
    'mysql+mysqlconnector://user:pwd@hostname/db_name?auth_plugin=mysql_native_password')
like image 123
Ilja Everilä Avatar answered Jan 23 '23 06:01

Ilja Everilä