To insert data from a pandas DataFrame into MySQL using executemany, you can follow these steps:
\

  1. Connect to the MySQL database using the mysql.connector module.\
  2. Create a cursor object to execute SQL queries.\
  3. Convert the DataFrame into a list of tuples using the to_records method.\
  4. Write an SQL INSERT statement with placeholders for the values.\
  5. Execute the SQL statement using executemany.

    Here's an example code snippet:
    \
import mysql.connector\
import pandas as pd\
\
# Connect to the MySQL database\
conn = mysql.connector.connect(\
    host="localhost",\
    user="your_username",\
    password="your_password",\
    database="your_database"\
)\
\
# Create a cursor object\
cursor = conn.cursor()\
\
# Read the DataFrame from a CSV file\
df = pd.read_csv("data.csv")\
\
# Convert the DataFrame into a list of tuples\
data = [tuple(row) for row in df.to_records(index=False)]\
\
# SQL INSERT statement\
sql = "INSERT INTO your_table (col1, col2, col3) VALUES (%s, %s, %s)"\
\
# Execute the SQL statement using executemany\
cursor.executemany(sql, data)\
\
# Commit the changes to the database\
conn.commit()\
\
# Close the cursor and connection\
cursor.close()\
conn.close()\
```\
\
Make sure to replace `your_username`, `your_password`, `your_database`, `your_table`, `col1`, `col2`, `col3` with your actual values.\
\
Note: This example assumes that your DataFrame columns match the columns in the MySQL table. If they don't match, you'll need to adjust the SQL INSERT statement and the DataFrame columns accordingly.

原文地址: https://www.cveoy.top/t/topic/pKdc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录