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

全國咨詢/投訴熱線:400-618-4000

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

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

好口碑IT培訓(xùn)

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

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

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

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

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

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

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

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

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

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


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

# 獲得游標(biāo)
cursor = conn.cursor()
# 創(chuàng)建數(shù)據(jù)庫
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)查詢employees表中字段emDepID的值為3的記錄,代碼如下。

# 查詢數(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('財務(wù)部一共有%d個員工' % 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)運行程序,程序執(zhí)行的結(jié)果如下所示:

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



猜你喜歡

python if條件判斷語句的用法

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

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

0 分享到:
和我們在線交談!