Python CSV to Database Import Guide

To import a CSV file into a database, you can use the pandas library in Python to read the CSV file and convert it into a DataFrame, and then use the SQLAlchemy library to connect to the database and insert the data from the DataFrame into a database table.

Here is an example code showing how to import a CSV file into a database.

import pandas as pd
from sqlalchemy import create_engine

# 读取CSV文件并转换为DataFrame
df = pd.read_csv('data.csv')

# 连接数据库
engine = create_engine('mysql://username:password@localhost/db_name') 

# 将DataFrame中的数据插入数据库表
df.to_sql('table_name', engine, if_exists='replace', index=False)

In the code above, the read_csv() function from the pandas library is first used to read the CSV file named data.csv and convert it into a DataFrame. Then, the create_engine() function from the SQLAlchemy library is used to connect to the database, and the to_sql() function is used to insert the data from the DataFrame into a database table named table_name. If the table already exists, the data in the existing table can be overwritten using the parameter if_exists=’replace’.

It is important to note that in the example code, the database connection string (‘mysql://username:password@localhost/db_name’) needs to be replaced with the actual database connection information.

bannerAds