知识点:
Python 元组 tuple() 函数将列表转换为元组。
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列
Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
tuple(i.strip().split(","))
首先创建一个数据库demo,在建立一个有no(自增),name,birthday,department的表student:
CREATE DATABASE demo;USE demo;CREATETABLE student( NO INT(11) PRIMARY KEY NOTNULL AUTO_INCREMENT, NAME VARCHAR(20)NOTNULL, birthday DATE, department VARCHAR(50)NOTNULL) ENGINE=INNODB DEFAULT CHARSET=utf8
demo.py代码如下(附有注释,请放心使用):
importpymysql'''#把TXT文件变成csvwith open("aa.txt","r") as a: data = a.readlines()with open("aa.csv","w") as b: for i in data: b.write(i)'''#读取csvwithopen("aa.csv","r") asc: data=c.readlines() data_list= [] foriindata: tp=tuple(i.strip().split(",")) data_list.append(tp) insert_list=data_list[1:] print(insert_list) withpymysql.connect(host='localhost', port=3306, user='root', password='1234', database='demo', charset='utf8') asconn: sql="INSERT INTO student values(NULL,%s,%s,%s)"cur=conn.cursor() cur.executemany(sql,insert_list) conn.commit()
返回mysql查看结果: