如何用python代码优雅地实现以下功能,从Excel读取数据,批量入mysql数据库 其中Excel的标题为acc_key,issuance_date,issuance_number,tracking_number,logistics_company_name,Excel的名称为shippment.XLS,Excel的路劲在当前目录下,mysql数据库的库为py,表名:logistics_trajectory,数据库对应的表字段名跟Excel一样,也是acc_key,issuance_date,issuance_number,tracking_number,logistics_company_name,IP:192.168.0.126,账号:root 密码:quc@2022@din
时间: 2024-03-23 10:44:08 浏览: 121
可以使用Python中的pandas和pymysql库来实现这个功能。具体实现步骤如下:
1. 导入所需库:
```
import pandas as pd
import pymysql
```
2. 读取Excel数据:
```
df = pd.read_excel('./shippment.xls')
```
其中,'./shippment.xls'是Excel文件的路径,可以根据实际情况进行修改。
3. 连接MySQL数据库:
```
conn = pymysql.connect(host='192.168.0.126', port=3306, user='root', password='quc@2022@din', db='py')
cursor = conn.cursor()
```
其中,host是MySQL的IP地址,user和password是登录MySQL时使用的用户名和密码,db是要连接的数据库名称。
4. 遍历Excel数据,插入到MySQL数据库中:
```
for index, row in df.iterrows():
acc_key = row['acc_key']
issuance_date = row['issuance_date']
issuance_number = row['issuance_number']
tracking_number = row['tracking_number']
logistics_company_name = row['logistics_company_name']
sql = "INSERT INTO logistics_trajectory(acc_key, issuance_date, issuance_number, tracking_number, logistics_company_name) \
VALUES ('%s', '%s', '%s', '%s', '%s')" % (acc_key, issuance_date, issuance_number, tracking_number, logistics_company_name)
cursor.execute(sql)
conn.commit()
```
其中,%s表示要插入的数据,这里使用了字符串格式化来构造SQL语句。
5. 关闭数据库连接:
```
cursor.close()
conn.close()
```
完整代码如下:
```
import pandas as pd
import pymysql
df = pd.read_excel('./shippment.xls')
conn = pymysql.connect(host='192.168.0.126', port=3306, user='root', password='quc@2022@din', db='py')
cursor = conn.cursor()
for index, row in df.iterrows():
acc_key = row['acc_key']
issuance_date = row['issuance_date']
issuance_number = row['issuance_number']
tracking_number = row['tracking_number']
logistics_company_name = row['logistics_company_name']
sql = "INSERT INTO logistics_trajectory(acc_key, issuance_date, issuance_number, tracking_number, logistics_company_name) \
VALUES ('%s', '%s', '%s', '%s', '%s')" % (acc_key, issuance_date, issuance_number, tracking_number, logistics_company_name)
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
```
阅读全文