mysql导入支持sql文件和txt文件(csv),但在txt直接导入会出现乱码,所以直接用python读取每一行,然后写入数据库。
最近看兄长生写jsp代码,逻辑运转之快让我们瞠目结舌,常年写代码才是技术积累的关键啊。不知道十年以后会不会像兄长这么牛逼。。。
下面贴代码:
python处理乱码主要有三步:
CREATE DATABASE xxx DEFAULT CHARACTER SET utf8
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='root',
db='test',
charset='utf8',
)
cur.execute(
"insert into data4(source_ip,source_port,des_ip,des_port,date,title) values(%s,%s,%s,%s,%s,%s)",
[output.source_ip, output.source_port, output.des_ip, output.des_port, output.date,
output_title.encode('utf-8')])
下面是完整代码:
#coding=utf-8
import MySQLdb
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='root',
db='test',
charset='utf8',
)
cur = conn.cursor()
f = open("new.txt", "r")
while True:
line = f.readline()
if line:
#处理每行\n
line = line.strip('\n')
line = line.split(",")
print line
tel = line[0]
province = line[1]
city = line[2]
call_type = line[3]
cur.execute(
"insert into data9(tel,province,city,cell_type) values(%s,%s,%s,%s)",
[tel, province, city, call_type])
else:
break
f.close()
cur.close()
conn.commit()
conn.close()