使用python将csv数据导入mysql数据库!
使用python将csv数据导入mysql数据库!

一、前言
在前面章节介绍过,我们处理的防火墙规则数据,数据清洗处理后,会产生几类表,以csv形式保存。在接下来的开发测试中,前台页面开始需要用到一些数据,此时我们就需要将csv中数据添加到mysql数据库中。在真实生产环境下,我们的防火墙规则可能数以万计,同时展开后的规则条数会更多,导入数据时间一般很长。这种情况下我们可以通过使用python脚本,放在后台自动导入。
二、python导入数据库示例
1、安装必要的库: 首先,确保已经安装了 pandas 和 mysql-connector-python 这两个库,可以使用 pip 进行安装:
|
1
|
pip install pandas mysql-connector-python |
2、连接到 MySQL 数据库: 在 Python 中,使用 mysql-connector-python 库连接到 MySQL 数据库:
|
1
2
3
4
5
6
7
8
9
10
11
12
|
import mysql.connector# 连接到 MySQL 数据库mydb = mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",database="yourdatabase")# 创建游标对象cursor = mydb.cursor() |
这里需要替换 localhost、yourusername、yourpassword 和 yourdatabase 为你的 MySQL 服务器地址、用户名、密码和数据库名称。
3、读取 CSV 文件: 使用 pandas 库读取 CSV 文件:
|
1
2
3
|
import pandas as pd# 读取 CSV 文件df = pd.read_csv("data.csv") |
4、将数据插入到 MySQL 数据库中:
|
1
2
3
4
5
6
7
|
# 遍历 DataFrame 中的每一行,并将数据插入到 MySQL 数据库中for index, row in df.iterrows():sql = "INSERT INTO your_table_name (column1, column2, column3, ...) VALUES (%s, %s, %s, ...)"values = (row['column1'], row['column2'], row['column3'], ...)cursor.execute(sql, values)# 提交更改mydb.commit() |
your_table_name 需要替换为目标表的名称, column1、column2、column3 等与 CSV 文件中的列名相对应。根据数据量,可以调整 SQL 查询和值的数量。
5、关闭连接: 在完成数据插入后,记得关闭连接:
|
1
2
3
|
# 关闭游标和数据库连接cursor.close()mydb.close() |
这样,就可以使用 Python 将 CSV 数据成功导入到 MySQL 数据库中了。确保在操作之前备份数据库以及 CSV 文件,以避免意外数据丢失。
三、防火墙查询页面数据导入脚本示例
sql.py
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
# -*- coding: UTF-8 -*import pymysql import time, datetimelocaldatetime= time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))print(localdatetime)print('开始导入数据!')def netfw_SQL():sql_conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',password='XXXXX', db='fwtest', charset='utf8', connect_timeout=1000)#创建数据库对象cursor = sql_conn.cursor()with open('netfirewalls.csv', encoding='utf-8') as line_1:#依次读取CSV文件的每一行for line_2 in line_1.readlines():#strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列line_2 = line_2.strip()#split() 通过指定分隔符对字符串进行切片,这里指定',',而“-1”表示分隔所有list_1 = line_2.split(',', -1)#执行插入表数据语句sql_2 = 'INSERT INTO netfirewalls (fwname, rulename, rulenum, description, action, disable, sourcezone, destzone, sourceip, destip, service) VALUE(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'cursor.execute(sql_2, (list_1[0], list_1[1], list_1[2], list_1[3], list_1[4], list_1[5], list_1[6], list_1[7], list_1[8], list_1[9], list_1[10]))sql_conn.commit() #提交事务sql_conn.close() #关闭连接localdatetime= time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))print(localdatetime)print('网络防火墙原规则数据导入完毕!')#执行自定义函数CSV_SQL()if __name__ == '__main__':netfw_SQL() |
到此这篇关于使用python将csv数据导入mysql数据库的文章就介绍到这了。
学习资料见知识星球。
以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。
快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利!
更多技巧, www.excelbook.cn
欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;
1、价值上万元的专业的PPT报告模板。
2、专业案例分析和解读笔记。
3、实用的Excel、Word、PPT技巧。
4、VIP讨论群,共享资源。
5、优惠的会员商品。
6、一次付费只需129元,即可下载本站文章涉及的文件和软件。
