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

查看:549
本文介绍了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)    

这篇关于python 批量导入文本文件到mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆