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

使用Python读取文件中的数据然后插入到mysql表中
在python中存在许多的第三方库操作MySQL,比如MySQLdb、pymysql等
MySQLdb是针对与python2的模块,还未曾支持python3
主要讲解一下pymysql这个模块

pymysql

安装模块

pip3 install pyMySQL

如果是windows下的Anaconda用户,可以打开Anaconda Prompt后使用命令

conda install PyMySQL

连接数据库

获取一个连接:connect()

connect = pymysql.connect(host,username,password,db_name)

获取游标对象:cursor()

cursor = connect.cursor()

执行sql语句:execute()

cursor.execute("show tables")

关闭资源:close()

cursor.close()
connect.close()

以上就是使用python对mysql的操作,基本流程就是使用这几个方法,关于查询或者创建等需求,只需要编写不同的sql语句即可

读取文件写入mysql

首先知道需要使用的方法
1、加载文件:open()

f = open("F:\\Done\\dic\\part-r-00000.txt", "r")

2、读取一行文件:readline()

line = f.readline()

3、切割字符:strip()、split()

line = line.strip('\n')   #取出每行首尾的空格回车
line = line.split(",")	  #按照“,”进行分割字符

编写代码

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))

以上代码就是从csv文件中处理每行数据写入mysql数据库中

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牧码文

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值