PyMySQL模块进行增删改查的操作。简单来讲,核心步骤有两步:链接数据库,读取CSV文件并导入数据表,然后查询数据,将数据表和计算结果导出为CSV文件。下面一起来具体看看吧~
Step1:安装PyMySQL模块
在正式动手之前,我们需要先安装PyMySQL模块。
(1)使用pip安装,清华镜像:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pymysql
(2)使用conda安装
conda install pymysql
Step2:从CSV文件导入数据到MySQL数据表
安装好以后,我们来进行第二步操作,从CSV文件导入数据到MySQL数据表。与内置的SQLite模块一样,PyMySQL也遵循DB-API规范,因此我们前面开发的大多数代码经过简单修改即可使用,以下代码中主要注释了与SQLite操作的不同之处。
#导入pymysql模块
import pymysql
#连接数据库,这里需要提供许多参数给connect方法
# host服务器ip地址
# user用户名password密码
# db数据库名称
cn = pymysql.connect(host='localhost', user='pandas', password='pandas', db='pandas')
# port端口 缺省值为3306
#新建游标对象 :和SQLite一样
cur = cn.cursor()
#建表SQL语句,小技巧: if not exists不会引起表已经存在的错误
# MySQL使用的是auto_increment, 注意有个下划线
artist_create_table = """
create table if not exists artist(
id integer primary key auto_increment not null,
name varchar(255)
)
"""
try:
cur.execute(artist_create_table)
print("成功建表")
except:
pass
#插入语句,使用%(id)s意味着我们会用字典对象替换数据
# PyMYSQL使用的语法是%(名称)s
artist_insert ="""
insert into artist(id, name) values ( %(id)s, %(name)s )
"""
#以下代码和SQLite一样
#导入csv模块
import csv
#用with语法,打开文件
with open('artist.csv', newline='') as csvfile:
#用DictReader类,方便开发
reader = csv.DictReader(csvfile)
#按行遍历csv文件
for row in reader:
try:
#按行执行SQL语句,注意,这里使用 字符串的format方法将数据替换进去
#如果可以相信数据的安全性可以这样做,如果数据来自互联网,需要用另一种更加安全的方式
cur.execute(artist_insert, {"id": row['id'], "name": row['name'] } )
except Exception as e:
print(e)
print("成功导入CSV数据" )
#提交事务
cn.commit()
#关闭数据库
cn.close()
Step3:将数据表与计算结果导出为CSV文件
接下来我们使用execute方法获取数据,然后输出到CSV文件,与SQLite代码类似:
#导入pymysql模块
import pymysql
#连接数据库
cn = pymysql.connect(host='localhost', user='pandas', password='pandas', db='pandas')
#新建游标对象
cur = cn.cursor()
#用with语法打开文件
with open("artist_data.csv", 'w') as csvfile:
#首先读取description写入CSV的第一行
#执行SQL语句
results= cur.execute("select * from artist")
#获得description
description = cur.description
#新建CSV writer对象
writer = csv.writer(csvfile)
#写入列名称
writer.writerow([ x[0] for x in description ] )
#遍历数据
for row in cur:
#写入每一行数据
writer.writerow(row)
print("成功写入CSV文件")
以上我们使用PyMySQL模块为例,介绍了如何使用Python对MySQL数据库进行增删改查,大家都学会了吗?