When attempting to write a Pandas DataFrame to a MySQL database using SQLAlchemy's to_sql method, you may encounter an error that resembles:
DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': Wrong number of arguments during string formatting
This error indicates a discrepancy in the SQL query being executed. Interestingly, it suggests an attempt to select from a SQLite database instead of MySQL.
To rectify this issue and establish the correct connection with MySQL using the SQLAlchemy engine and mysqlconnector, follow these steps:
import pandas as pd import mysql.connector from sqlalchemy import create_engine # Create SQLAlchemy engine engine = create_engine('mysql+mysqlconnector://[user]:[pass]@[host]:[port]/[schema]', echo=False) # Read and write using the engine connection data = pd.read_sql('SELECT * FROM sample_table', engine) data.to_sql(name='sample_table2', con=engine, if_exists='append', index=False)
This modification ensures that the connection used for both reading and writing is the SQLAlchemy engine connected to MySQL. It eliminates the initial attempt to use a raw connection, which may have triggered the SQLite-related error.
The above is the detailed content of Why Does Pandas\' to_sql Fail with a \'Wrong Number of Arguments\' Error When Writing to MySQL?. For more information, please follow other related articles on the PHP Chinese website!