首页 > 数据库 > MySQL > 正文

Linux中将txt导入到mysql的方法教程

2024-07-24 12:54:14
字体:
来源:转载
供稿:网友

前言

昨天写小项目的时候遇到了一个需求:把txt文档的数据导入到mysql数据库中,开始本来想直接用Mysql Workbench导入TXT文件,但是最后发现不支持TXT导入,结果我吧嗒吧嗒的去把TXT转了Excel,拿到Linux上导入的时候又发现了各种乱码问题。

抱着没有什么是程序员干不了的原则,我手写了一个Python代码直接操作文件进行导入了。结果大概一万多条的文件,导入时间大概两分钟。

下面是具体的代码:

mysqlpython.py文件:  自定义的连接mysql数据库的类 importtxt.py文件: 读TXT文件并进行插入操作 dict.txt文件: 要操作的TXT文件

mysqlpython.py文件

from pymysql import *class Mysqlpython: def __init__(self,database,host="localhost", user="root",password="123456", charset="utf8",port=3306): self.database = database self.host = host self.user = user self.password = password self.charset = charset self.port = port # 创建数据连接和游标对象 def open(self): self.db = connect(host=self.host, user=self.user, password=self.password, port=self.port, database=self.database, charset=self.charset) self.cur = self.db.cursor() # 关闭游标对象和数据库连接对象 def close(self): self.cur.close() self.db.close() # 执行sql命令 def zhixing(self,sql,L=[]): self.open() self.cur.execute(sql,L) self.db.commit() self.close() # 查询功能 def all(self,sql,L=[]): self.open() self.cur.execute(sql,L) result = self.cur.fetchall() return resultif __name__ == "__main__": sqlh = Mysqlpython("dictionary") sel = "select * from user" r = sqlh.all(sel) print(r)

importtxt.py文件

import reimport sysfrom mysqlpython import Mysqlpythonsqlh = Mysqlpython("dictionary")def insert(data): arr = data.split() name = arr[0] description = " ".join(arr[1:]) ins = "insert into words(name,description) values(%s,%s)" sqlh.zhixing(ins,[name,description])def get_addr(): f = open('./dict.txt') lines=f.readlines() for line in lines: insert(line) f.close() return ''if __name__ =='__main__': print(get_addr())

dict.py文件(我复制了几条文件)

a indef art oneabacus n.frame with beads that slide along parallel rods, used for teaching numbers to children, and (in some countries) for countingabandon v. go away from (a person or thing or place) not intending to return; forsake; desertabandonment n. abandoningabase v. ~ oneself/sb lower oneself/sb in dignity; degrade oneself/sb ;abash to destroy the self-possession or self-confidence of:disconcertabashed adj. ~ embarrassed; ashamedabate v. make or become lessabattoir n. = slaughterhouse (slaughter)

针对不同的分隔符修改一下正则表达式即可。全部代码都贴上去了,直接复制修改下数据库的配置就可以运行了。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表