一、参考资料
Python将csv文件数据保存到MySQL中_weixin_43351935的博客-CSDN博客
二、源代码
import pymysql import pandas as pd def run_sql(path): connection = pymysql.connect( host='192.168.31.104', user='root', password='1234', db='amazon_us', charset='utf8' ) cursor = connection.cursor() file=open(path,encoding='utf-8') #文件路径有中文,所以,先使用open打开一下 df=pd.read_csv(file,encoding='utf-8') print(df.head()) for i in range(df.shape[0]): data=df.iloc[i] data=(data['keyword'],data['link_detail'],data['search_num'],data['url']) sql = "insert into amazon_us_link(keyword,link_detail,search_num,url) values " + str(data) + ";" #要与表的机构对其。第一个是主键,自增长的。 print(sql) try: cursor.execute(sql) #执行sql语句 connection.commit() #连接提交 except: connection.rollback() cursor.close() connection.close() return if __name__ == '__main__': path=r'E:databasedata.csv' run_sql(path)