A8站长源码生意途径
我这边是运用pandas和pymysql来完毕将csv文件导入到MySQL数据库的
首先说一下完毕逻辑,就是将csv读取到dataframe中,然后把按行读取数据,将每行的数据添加到列表中,在运用pymysql这个包将数据添加到数据库。A8站长源码生意途径
代码如下:
import pandas as pd
import pymysql
#读取数据
test = pd.read_csv(r'Antai_AE_round1_item_attr_20190626/Antai_AE_round1_item_attr_20190626.csv')
test.head()
#联接数据库
db = pymysql.connect(host="IP地址",user="数据库用户名", passwd="暗码",db="要联接的数据库",charset='utf8')
#定义操作函数
def insert_deta():
list1 = []
num = 0
cursor = db.cursor()
for i in range(0,test.shape[0]): # 运用shape的第一个元历来获取数据的数量
row_data = test.iloc[i] # 获取第每行数据
value = (str(row_data[0]),str(row_data[1]),str(row_data[2]),str(row_data[3])) #读取第每行中每列数据,因为数据库添加运用的都是字符串方法添加故都取str
list1.append(value)
num +=1
if num==10000:
sql = "INSERT INTO item(item_id,cate_id,store_id,item_price)VALUES(%s,%s,%s,%s)"
cursor.executemany(sql, list1) # 施行sql语句
db.commit()
num = 0 # 计数归零
list1.clear() # 清空list
cursor.close() # 关闭联接
db.close()
#施行函数
insert_deta()
A8站长源码生意途径
其间需求说明的是,要完毕上述操作,需求先在数据库建好你要导入的那张表。其次我对代码进行了必定的优化,因为添加到数据库是一个耗时操作,所以我运用executemany方法将数据以每10000条来添加到数据库,跋涉功率。
A8站长源码生意途径
其间我的数据库类型是:

终究存入数据后: