首页 > python 批量导入文本文件到mysql数据库

python 批量导入文本文件到mysql数据库

现有文本文件如下:都是IP地址,想使用python 批量导入到mysql数据库.
218.61.30.195
61.161.255.125
221.203.162.178
218.60.142.66
61.161.214.237
60.18.250.166
原来使用delphi编写的,现在不想调试了,就是想每行读入,生成sql语句,然后插入到mysql数据库的表中.原来的delphi程序如下:
procedure TForm1.Button2Click(Sender: TObject);
var i: integer;
s,qs,qs1:String;
begin
if OpenDialog1.Execute then begin

memo1.Lines.Clear;
memo2.lines.clear;
memo1.Lines.loadfromfile(opendialog1.FileName);

end;
adoconnection1.Connected:=true;
qs:='insert into ips (ip,ipint,city,createtime) values ("';
for i := 0 to Memo1.Lines.Count-1 do
begin
s:=Memo1.Lines.Strings[i];
qs1:=qs+s;
qs1:=qs1+'",inet_aton("'+s+'"),null,now()); ';
Memo2.Lines.Add(qs1);
adoquery1.close();
adoquery1.sql.clear;
adoquery1.sql.add(qs1);
adoquery1.execsql;
end;
application.messagebox('批量添加IP地址成功!','提示',0+64);
end;
想在使用
f=open("c:\20160428_shoukong.txt",'r')
for eachline in f:

s='insert into ips (ip,ipint) values ('')'
print eachline,

f.close()

步骤我的理解是:
第一读入文件 并存入到
生成sql语句,
关闭读取的文件
关闭数据库连接.请各位大侠帮看一下


#coding=utf-8

import MySQLdb

def db_execute(sql):
    dbs = MySQLdb.connect(host='你的ip', user='帐号', passwd='密码', db='数据库', port=3306)
    cursor = dbs.cursor()
    cursor.execute(sql)
    cursor.close()


def read_file(file_path):
    sql_lines = []
    with open(file_path, 'r') as file:
        for line in file.readlines():
            sql = 'insert table(field) values({0});'.format(line)
            sql_lines.append(sql)

    return '\r\n'.join(sql_lines)

sql_lines = read_file('a.txt')
db_execute(sql_lines)    


其中一张图片是程序 import mysqldb没有问题,已经测试过了
其中第二张照片是需要导入的文本文件,当然是ip地址
第三张图片是报错信息 ,其实我在程序中有一句是打印出print sql_lines ,将其中一句在mysql插入是没有问题的,但是不知道出现在哪里.

请各位在百忙中看一下


你好!有一点小小的建议,如果你有现成的文本文件,建议在mysql中使用
“Load Data Infile” 命令,这样效率更高!
相关链接:(1)http://blog.sina.com.cn/s/blog_97688f8e0101hgfx.html

     (2)http://blog.csdn.net/vbloveshllm/article/details/42965317
【热门文章】
【热门文章】