python读取文件中的数据插入到mysql

Posted on   风行天下-2080  阅读(860)  评论(0编辑  收藏  举报

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、

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2018-05-10 linux计划任务crontab的使用
2018-05-10 python 编写远程连接服务器脚本

随笔 - 618, 文章 - 0, 评论 - 6, 阅读 - 37万

Copyright © 2025 风行天下-2080
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示