1. 程式人生 > 其它 >python讀取檔案中的資料插入到mysql

python讀取檔案中的資料插入到mysql

1、python讀取檔案中的資料插入到mysql

https://blog.csdn.net/weixin_46429290/article/details/119303393?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-0-119303393-blog-79304146.pc_relevant_antiscanv2&spm=1001.2101.3001.4242.1&utm_relevant_index=3

使用Python讀取檔案中的資料然後插入到mysql表中
在python中存在許多的第三方庫操作MySQL,比如MySQLdb、pymysql等
MySQLdb是針對與python2的模組,還未曾支援python3
主要講解一下pymysql這個模組

pymysql
安裝模組
pip3 install pyMySQL
1
如果是windows下的Anaconda使用者,可以開啟Anaconda Prompt後使用命令

conda install PyMySQL
1
連線資料庫
獲取一個連線:connect()

connect = pymysql.connect(host,username,password,db_name)
1
獲取遊標物件:cursor()

cursor = connect.cursor()
1
執行sql語句:execute()

cursor.execute("show tables")
1
關閉資源:close()

cursor.close()
connect.close()
1
2
以上就是使用python對mysql的操作,基本流程就是使用這幾個方法,關於查詢或者建立等需求,只需要編寫不同的sql語句即可

讀取檔案寫入mysql
首先知道需要使用的方法
1、載入檔案:open()

f = open("F:\\Done\\dic\\part-r-00000.txt", "r")
1
2、讀取一行檔案:readline()

line = f.readline()
1
3、切割字元:strip()、split()

line = line.strip('\n') #取出每行首尾的空格回車
line = line.split(",") #按照“,”進行分割字元
1
2
編寫程式碼

import pymysql
from time import time

host="localhost"
port=3306
username="root"
password="000000"
db_name="AIS202002"


conn = pymysql.connect(host=host,port=port,user=username,passwd=password,db=db_name)
cur = conn.cursor()
f = open("F:\\Done\\dic\\part-r-00000.txt", "r")
start_time = time()
while True:
line = f.readline()
if line:
#處理每行\n
line = line.strip('\n')
line = line.split(",")

MMSI = line[0]
shipType = line[1]
nacStatusEN = line[2]
draught = line[3]
heading = line[4]
course = line[5]
speed = line[6]
dest = line[7]
unixTime = line[8]
lon_d = line[9]
lat_d = line[10]
seaRange = line[11]

try:
cur.execute("insert into CargoShip(MMSI,shipType,nacStatusEN,draught,heading,course,speed,dest,unixTime,lon_d,lat_d,seaRange)"
"values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
[MMSI,shipType,nacStatusEN,draught,heading,course,speed,dest,unixTime,lon_d,lat_d,seaRange])
print("成功插入一條資料")
except Exception as e:
conn.rollback()
print("there is a error!")
else:
break
f.close()
cur.close()
conn.commit()
conn.close()
end_time = time()
print("總共執行了 {} 秒!".format(end_time - start_time))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
以上程式碼就是從csv檔案中處理每行資料寫入mysql資料庫中
————————————————
版權宣告:本文為CSDN博主「牧碼文」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/weixin_46429290/article/details/119303393

2、