Home > Database > Mysql Tutorial > Can I Directly Insert a Pandas DataFrame into MySQL Using mysqldb?

Can I Directly Insert a Pandas DataFrame into MySQL Using mysqldb?

Linda Hamilton
Release: 2024-12-05 20:42:17
Original
646 people have browsed it

Can I Directly Insert a Pandas DataFrame into MySQL Using mysqldb?

Inserting a Pandas Dataframe into a MySQL Database using mysqldb

Question:

Can mysqldb be used to directly insert a complete Pandas dataframe into an existing MySQL table, or does it require iteration over the dataframe rows?

Answer:

Yes, mysqldb can be used to insert a dataframe into an existing MySQL table without the need for row iteration. Here's how you can do it:

Importing Libraries and Establishing MySQL Connection:

from pandas.io import sql
import MySQLdb

# Connect to MySQL database
con = MySQLdb.connect(host="localhost", user="root", password="password", database="your_database")
Copy after login

Inserting Dataframe into Table:

You can use the sql.write_frame function of Pandas to write the dataframe into the MySQL table.

# Create a dataframe
df = pd.DataFrame({'ID': [1, 2, 3], 'Data1': [4, 5, 6], 'Data2': [7, 8, 9]})

# Write dataframe to table
sql.write_frame(df, con=con, name='your_table_name', if_exists='replace', flavor='mysql')
Copy after login

In the above code:

  • con: Represents the established MySQL connection.
  • name: Name of the table in the database into which the dataframe is to be inserted.
  • if_exists: Defines how to handle an existing table. Options are 'fail', 'replace', and 'append'. 'replace' drops the existing table and recreates it with the dataframe's data.
  • flavor: Specifies the database flavor, in this case, 'mysql'.

Using the to_sql Method:

Alternatively, you can also use the newer to_sql method in Pandas:

df.to_sql(con=con, name='your_table_name', if_exists='replace', flavor='mysql')
Copy after login

Notes:

  • The flavor argument should be set to 'mysql' for inserting into a MySQL database.
  • The if_exists argument can be set to 'fail' to raise an error if the table already exists, 'replace' to drop and recreate the table, or 'append' to insert into an existing table.
  • MySQLdb is recommended for Python versions 2.7 and 3.5. For Python 3.6 and higher, consider using PyMySQL or mysqlclient.

The above is the detailed content of Can I Directly Insert a Pandas DataFrame into MySQL Using mysqldb?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template