excel自带转txt功能,转的时候要改成utf-8
我的数据是两列(table_1,table_2), 转成的数据按行读取然后insert
其实还是用pandas的to_sql方便快捷
import pymysql
db = pymysql.connect(host = "localhost",
port = 3306,
user = "usr_name",
passwd = "passwd",
db = "database_name",
charset="utf8")
cursor = db.cursor()
with open (r"d:\\inf_import.txt","r",encoding = "utf8") as f:
for line in f:
data = line.strip("\n").split("\t")
sql = "INSERT INTO table_name (table_1, table_2) VALUES (%s, %s)"
try:
cursor.execute(sql, [data[0],data[1]]) # 执行sql语句
db.commit()
except:
db.rollback()# 发生错误时回滚
# 关闭数据库连接
db.close()