教育行業(yè)A股IPO第一股(股票代碼 003032)

全國(guó)咨詢(xún)/投訴熱線:400-618-4000

Python如何使用pymysql鏈接mysql數(shù)據(jù)庫(kù)?

更新時(shí)間:2020年12月11日11時(shí)17分 來(lái)源:傳智教育 瀏覽次數(shù):

好口碑IT培訓(xùn)

Python如何使用pymysql鏈接mysql數(shù)據(jù)庫(kù)?使用pymysql庫(kù)訪問(wèn)MySQL數(shù)據(jù)庫(kù)可分為以下幾步:

(1)創(chuàng)建連接。通過(guò)connect()方法創(chuàng)建用于連接數(shù)據(jù)庫(kù)的Connection對(duì)象。

(2)獲取游標(biāo)。通過(guò)Connection對(duì)象的cursor()方法創(chuàng)建Cursor對(duì)象。

(3)執(zhí)行SQL語(yǔ)句。通過(guò)Cursor對(duì)象的execute()、fetchone()或fetchall()方法執(zhí)行SQL語(yǔ)句,實(shí)現(xiàn)數(shù)據(jù)庫(kù)基本操作,包括數(shù)據(jù)的增加、更新、刪除、查詢(xún)等。

(4)關(guān)閉游標(biāo)。通過(guò)Cursor對(duì)象的close()方法關(guān)閉游標(biāo)。

(5)關(guān)閉連接。通過(guò)Connection對(duì)象的close()方法關(guān)閉連接。獲取【Python視頻教程+筆記+源碼】加播妞1605146928606_課程資料.jpg:435946716。

下面按照以上介紹的流程,通過(guò)一個(gè)示例分步驟為大家演示如何使用pymysql操作MySQL數(shù)據(jù)庫(kù),具體內(nèi)容如下。

(1)導(dǎo)入pymysql庫(kù),創(chuàng)建程序與MySQL數(shù)據(jù)庫(kù)的連接,代碼如下。

import pymysql
# 連接數(shù)據(jù)庫(kù)
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='123456',
    charset='utf8'
)

以上代碼連接本地的MySQL數(shù)據(jù)庫(kù),并以root用戶(hù)的身份訪問(wèn)該數(shù)據(jù)庫(kù)。


(2)創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)dbtest,并在數(shù)據(jù)庫(kù)dbtest中創(chuàng)建一張表示員工信息的數(shù)據(jù)表employees。數(shù)據(jù)表employees中共有emID、emName、emLevel、emDepID這4個(gè)字段,其中字段被設(shè)置為主鍵,代碼如下。

# 獲得游標(biāo)
cursor = conn.cursor()
# 創(chuàng)建數(shù)據(jù)庫(kù)
sql_create = "create database if not exists dbtest"
cursor.execute(sql_create)
# 創(chuàng)建數(shù)據(jù)表
sql_use = 'use dbtest'
cursor.execute(sql_use)
sql_table = 'create table if not exists employees(emID int primary key,
emName varchar(20), emLevel varchar(20), emDepID varchar(20))'
cursor.execute(sql_table)

(3)向數(shù)據(jù)表employees中插入一條記錄,代碼如下。

# 插入數(shù)據(jù)
sql = "insert into employees (emID, emName, emLevel, emDepID)
    values (%d, '%s', %d, %d)"
data = (15, '小園', 3, 3)
cursor.execute(sql % data)
conn.commit()


(4)更新數(shù)據(jù)表employees,將字段emID的值為15的記錄中字段emName的值修改為“小丸子”,代碼如下。

# 修改數(shù)據(jù)
sql = "update employees set emName = '%s' where emID = %d"
data = ('小丸子', 15)
cursor.execute(sql % data)
conn.commit()

(5)查詢(xún)employees表中字段emDepID的值為3的記錄,代碼如下。

# 查詢(xún)數(shù)據(jù)
sql = "select emID, emName from employees where emDepID = 3"
cursor.execute(sql)
for row in cursor.fetchall():
print("員工ID:%d 姓名:'%s'" % row)
print('財(cái)務(wù)部一共有%d個(gè)員工' % cursor.rowcount)


(6)刪除employees表中字段emID的值為15的一條記錄,代碼如下。

# 刪除數(shù)據(jù)
sql = "delete from employees where emID = %d limit %d"
data = (15, 1)
cursor.execute(sql % data)
conn.commit()
print('共刪除%d條數(shù)據(jù)' % cursor.rowcount)


(7)關(guān)閉游標(biāo)和連接,代碼如下。

cursor.close() # 關(guān)閉游標(biāo)
conn.close() # 關(guān)閉連接


(8)運(yùn)行程序,程序執(zhí)行的結(jié)果如下所示:

員工ID:15 姓名:'小丸子'
財(cái)務(wù)部一共有1個(gè)員工
共刪除1條數(shù)據(jù)



猜你喜歡

python if條件判斷語(yǔ)句的用法

Python 中strip()方法怎么用?去除空白字符和指定字符

python+數(shù)據(jù)分析培訓(xùn)課程

0 分享到:
和我們?cè)诰€交談!