如何使用PyMySQL模組進行增刪改查?

2021-10-24 03:18:33 字數 2411 閱讀 5917

mysql 是目前最為流行的關係型資料庫。接下來我們通過乙個簡單的案例,練習如何使用 pymysql 模組進行增刪改查的操作。簡單來講,核心步驟有兩步:鏈結資料庫,讀取 csv 檔案並匯入資料表,然後查詢資料,將資料表和計算結果匯出為 csv 檔案。下面一起來具體看看吧~

用pymysql模組增刪改查

step1: 安裝 pymysql 模組

在正式動手之前,我們需要先安裝 pymysql 模組。

(1)使用 pip 安裝, 清華映象:

pip install -i pymysql

(2)使用 conda 安裝

conda install pymysql

step2: 從 csv 檔案匯入資料到 mysql 資料表

安裝好以後,我們來進行第二步操作,從 csv 檔案匯入資料到 mysql 資料表。與內建的 sqlite 模組一樣, pymysql 也遵循 db-api 規範,因此我們前面開發的大多數**經過簡單修改即可使用,以下**中主要注釋了與 sqlite 操作的不同之處。

import pymysql

cn = pymysql.connect(host=『localhost』, user=『pandas』, password=『pandas』, db=『pandas』)

cur = cn.cursor()

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
artist_insert ="""

insert into artist(id, name) values ( %(id)s, %(name)s )

import csv

with open(『artist.csv』, newline=』』) as csvfile:

# 用 dictreader 類, 方便開發

reader = csv.dictreader(csvfile)

# 按行遍歷csv 檔案

for row in reader:

try:

# 按行執行 sql 語句, 注意, 這裡使用 字串的format方法將資料替換進去

# 如果可以相信資料的安全性可以這樣做, 如果資料來自網際網路, 需要用另一種更加安全的方式

cur.execute(artist_insert, )

except exception as e:

print(e)

print(" 成功匯入 csv 資料" )

cn.commit()

cn.close()

step3: 將資料表與計算結果匯出為 csv 檔案

接下來我們使用 execute 方法獲取資料,然後輸出到 csv 檔案,與 sqlite **類似:

import pymysql

cn = pymysql.connect(host=『localhost』, user=『pandas』, password=『pandas』, db=『pandas』)

cur = cn.cursor()

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 資料庫進行增刪改查,大家都學會了嗎?

PyMySQL模組的使用

pip3 install pymysqlimport pymysql 建立連線 conn pymysql.connect host 127.0.0.1 port 3306,user root password 123456 db db5 charset utf8 user input user pw...

pymysql模組用法

pymsql是python中操作mysql的模組,其使用方法和py2的mysqldb幾乎相同。1 pip install pymysql import pymysql 新增資料 conn pymysql.connect host 127.0.0.1 port 3306,user root passw...

pymysql 模組介紹

pymysql模組是python與mysql進行互動的乙個模組。pymysql模組的安裝 pymysql模組的用法 import pymysql user input user strip pwd input pwd strip conn pymysql.connect host localhost...