现有文本文件如下:都是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语句,
关闭读取的文件
关闭数据库连接.请各位大侠帮看一下
Hello! A little suggestion, if you have a ready-made text file, it is recommended to use the
"Load Data Infile" command in mysql, which is more efficient!
Related links: (1) http://blog.sina.com.cn/s/blog_97688f8e0101hgfx.html
One of the pictures is the program import mysqldb, there is no problem, it has been tested
The second picture is the text file that needs to be imported, of course the IP address
The third picture is the error message, in fact, I am in the program One of the sentences prints out print sql_lines. There is no problem inserting one of the sentences into mysql, but I don’t know where it appears.
Please take a look during your busy schedule