在眾多數(shù)據(jù)庫當(dāng)中,我們比較熟悉的就是MySQL。MySQL也是當(dāng)前較為流行的關(guān)系型數(shù)據(jù)庫。但是很多人在使用MySQL進(jìn)行增刪改查時(shí),不知道要怎么做。經(jīng)常使用MySQL數(shù)據(jù)庫的人都清楚,想要進(jìn)行這個(gè)操作還是非常簡單的,只需要簡單的兩步即可完成,即連接數(shù)據(jù)庫,同時(shí)在讀取CSV文件時(shí),導(dǎo)入數(shù)據(jù)表;然后將查詢數(shù)據(jù),并將數(shù)據(jù)表和計(jì)算結(jié)果導(dǎo)出為 CSV 文件。以下是詳細(xì)操作過程:
Step1: 安裝 PyMySQL 模塊
在正式動(dòng)手之前,我們需要先安裝 PyMySQL 模塊。
(1)使用 pip 安裝, 清華鏡像:
pip install -i https://xxx pymysql
(2)使用 conda 安裝
conda install pymysql
Step2: 從 CSV 文件導(dǎo)入數(shù)據(jù)到 MySQL 數(shù)據(jù)表
安裝好以后,我們來進(jìn)行第二步操作,從 CSV 文件導(dǎo)入數(shù)據(jù)到 MySQL 數(shù)據(jù)表。與內(nèi)置的 SQLite 模塊一樣, PyMySQL 也遵循 DB-API 規(guī)范,因此我們前面開發(fā)的大多數(shù)代碼經(jīng)過簡單修改即可使用,以下代碼中主要注釋了與 SQLite 操作的不同之處。
# 導(dǎo)入 pymysql 模塊
import pymysql
# 連接數(shù)據(jù)庫, 這里需要提供許多參數(shù)給 connect 方法
# host 服務(wù)器ip地址
# user 用戶名 password 密碼
# db 數(shù)據(jù)庫名稱
cn = pymysql.connect(host='localhost', user='pandas', password='pandas', db='pandas')
# port 端口 缺省值為 3306
# 新建游標(biāo)對(duì)象 :和 SQLite 一樣
cur = cn.cursor()
# 建表SQL語句, 小技巧: if not exists 不會(huì)引起表已經(jīng)存在的錯(cuò)誤
# MySQL 使用的是 auto_increment , 注意有個(gè)下劃線
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 意味著我們會(huì)用字典對(duì)象替換數(shù)據(jù)
# PyMYSQL 使用的語法是 %(名稱)s
artist_insert ="""
insert into artist(id, name) values ( %(id)s, %(name)s )
"""
# 以下代碼和 SQLite 一樣
# 導(dǎo)入 csv 模塊
import csv
# 用 with 語法, 打開文件
with open('artist.csv', newline='') as csvfile:
# 用 DictReader 類, 方便開發(fā)
reader = csv.DictReader(csvfile)
# 按行遍歷csv 文件
for row in reader:
try:
# 按行執(zhí)行 SQL 語句, 注意, 這里使用 字符串的format方法將數(shù)據(jù)替換進(jìn)去
# 如果可以相信數(shù)據(jù)的安全性可以這樣做, 如果數(shù)據(jù)來自互聯(lián)網(wǎng), 需要用另一種更加安全的方式
cur.execute(artist_insert, {"id": row['id'], "name": row['name'] } )
except Exception as e:
print(e)
print(" 成功導(dǎo)入 CSV 數(shù)據(jù)" )
# 提交事務(wù)
cn.commit()
# 關(guān)閉數(shù)據(jù)庫
cn.close()
Step3: 將數(shù)據(jù)表與計(jì)算結(jié)果導(dǎo)出為 CSV 文件
接下來我們使用 execute 方法獲取數(shù)據(jù),然后輸出到 CSV 文件,與 SQLite 代碼類似:
# 導(dǎo)入 pymysql 模塊
import pymysql
# 連接數(shù)據(jù)庫
cn = pymysql.connect(host='localhost', user='pandas', password='pandas', db='pandas')
# 新建游標(biāo)對(duì)象
cur = cn.cursor()
# 用 with語法打開文件
with open("artist_data.csv", 'w') as csvfile:
# 首先讀取 description 寫入 CSV 的第一行
# 執(zhí)行 SQL 語句
results= cur.execute("select * from artist")
# 獲得 description
description = cur.description
# 新建 CSV writer 對(duì)象
writer = csv.writer(csvfile)
# 寫入列名稱
writer.writerow([ x[0] for x in description ] )
# 遍歷數(shù)據(jù)
for row in cur:
# 寫入每一行數(shù)據(jù)
writer.writerow(row)
print(" 成功寫入 CSV 文件")
通過上述介紹,PyMySQL要增刪改查要怎么做相信大家已經(jīng)清楚了吧,想了解更多關(guān)于PyMySQL數(shù)據(jù)庫的信息,請(qǐng)繼續(xù)關(guān)注中培偉業(yè)。