Python批量写入数据到MySQL

Python批量写入数据到MySQL

​ 之前在工作中,遇到一个大批量数据需要写到MySQL数据库中的工作,当时就用Python简单实现了一下。

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'''批量将Excel数据写入MySQL'''
import pymysql
import xlrd

def mysql_link(db_name):
'''
连接数据库
guest:数据库名称
return:db
'''
try:
db = pymysql.connect(host='192.168.0.*',
user='username',
passwd='password',
db=db_name,
charset='utf8mb4')
return db
except ConnectionError as e:
print("数据库连接异常!" + str(e))

def open_excel(excel_file):
'''
读取Excel函数
excel_file:表格文件路径
return:book
'''
try:
book = xlrd.open_workbook(excel_file) # 同一目录下
return book
except Exception as e:
print(str(e))

def store_to(db_name, table_name, file_url):
'''
执行插入操作
db_name(数据库名称)
table_name(表名称)
excel_file(excel文件名,把文件与py文件放在同一目录下)
'''
db = mysql_link(db_name) # 打开数据库连接
cursor = db.cursor() # 使用 cursor() 方法创建一个游标对象 cursor

book = open_excel(file_url) # 打开excel文件
sheets = book.sheet_names() # 获取所有表名
for sheet in sheets:
sh = book.sheet_by_name(sheet) # 打开每一张表
row_nuw = sh.nrows
print(row_nuw - 1)
listdata = [] # 定义列表原来存放数据
for i in range(1, row_nuw): # 表格首行title对应插入对应表的字段名
row_data = sh.row_values(i) # 按行获取Excel的值
listdata.append(row_data) # 将数据暂存在list
print(listdata)
sql = "INSERT INTO " + table_name + "(tracking_name, tracking_no, create_date, sort_num, del_flag) " \
"VALUES (%s, %s, %s, %s, %s)"
cursor.executemany(sql, listdata) # 执行SQL语句
db.commit()
listdata.clear()
print('插入成功!' + '共计' + str(row_nuw - 1) + '条数据!')
cursor.close()
db.close()


if __name__ == '__main__':
store_to('cccivaoperate', 't_tracking', '快递.xlsx')

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×