您好,登錄后才能下訂單哦!
前言
昨天寫小項目的時候遇到了一個需求:把txt文檔的數(shù)據(jù)導入到mysql數(shù)據(jù)庫中,開始本來想直接用Mysql Workbench導入TXT文件,但是最后發(fā)現(xiàn)不支持TXT導入,結果我吧嗒吧嗒的去把TXT轉(zhuǎn)了Excel,拿到Linux上導入的時候又發(fā)現(xiàn)了各種亂碼問題。
抱著沒有什么是程序員干不了的原則,我手寫了一個Python代碼直接操作文件進行導入了。結果大概一萬多條的文件,導入時間大概兩分鐘。
下面是具體的代碼:
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 # 創(chuàng)建數(shù)據(jù)連接和游標對象 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() # 關閉游標對象和數(shù)據(jù)庫連接對象 def close(self): self.cur.close() self.db.close() # 執(zhí)行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 result if __name__ == "__main__": sqlh = Mysqlpython("dictionary") sel = "select * from user" r = sqlh.all(sel) print(r)
importtxt.py文件
import re import sys from mysqlpython import Mysqlpython sqlh = 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 one abacus n.frame with beads that slide along parallel rods, used for teaching numbers to children, and (in some countries) for counting abandon v. go away from (a person or thing or place) not intending to return; forsake; desert abandonment n. abandoning abase v. ~ oneself/sb lower oneself/sb in dignity; degrade oneself/sb ; abash to destroy the self-possession or self-confidence of:disconcert abashed adj. ~ embarrassed; ashamed abate v. make or become less abattoir n. = slaughterhouse (slaughter)
針對不同的分隔符修改一下正則表達式即可。全部代碼都貼上去了,直接復制修改下數(shù)據(jù)庫的配置就可以運行了。
總結:
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。