如何将utf8csv文件写入mysql
时间: 2024-09-23 13:03:59 浏览: 32
将UTF-8编码的CSV文件写入MySQL数据库,通常需要经过几个步骤:
1. **读取CSV文件**:
使用Python的`pandas`库可以轻松读取CSV文件,例如:
```python
import pandas as pd
df = pd.read_csv('your_utf8_file.csv', encoding='utf-8')
```
2. **连接到MySQL**:
使用如`pymysql`或`mysql-connector-python`这样的库来连接MySQL数据库:
```python
import pymysql
connection = pymysql.connect(host='localhost', user='your_username', password='your_password', db='your_database')
```
3. **数据预处理**:
确保DataFrame中的数据结构适合插入到MySQL表中,比如日期转换、数值类型确认等。
4. **批量插入**:
将数据帧`df`转换成SQL插入语句,并分批执行以避免一次性写入大量数据导致内存溢出:
```python
def to_sql(df, table_name):
with connection.cursor() as cursor:
for i in range(0, len(df), chunk_size): # 分块操作
chunk_df = df.iloc[i:i+chunk_size]
insert_query = "INSERT INTO {} ({}) VALUES {}".format(table_name, ', '.join(chunk_df.columns), ', '.join(['%s'] * len(chunk_df.columns)))
cursor.executemany(insert_query, chunk_df.values.tolist())
connection.commit()
```
5. **关闭连接**:
最后别忘了关闭数据库连接:
```python
connection.close()
```
阅读全文