python 批量导入文本文件到mysql数据库
黄舟
黄舟 2017-04-17 17:44:44
0
3
604

现有文本文件如下:都是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语句,
关闭读取的文件
关闭数据库连接.请各位大侠帮看一下

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
PHPzhong
#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)    
黄舟

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

     (2)http://blog.csdn.net/vbloveshllm/article/details/42965317
黄舟


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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template