Python進(jìn)階(二十二)-Python3使用PyMysql連接mysql數(shù)據(jù)庫(kù)

      網(wǎng)友投稿 902 2022-05-30

      #Python進(jìn)階(二十二)-Python3使用PyMysql連接mysql數(shù)據(jù)庫(kù)

      python語(yǔ)言的3.x完全不向前兼容,導(dǎo)致我們?cè)趐ython2.x中可以正常使用的庫(kù),到了python3就用不了.比如說(shuō)mysqldb。

      目前MySQLdb并不支持python3.x,Python3.x連接MySQL的方案有:oursql, PyMySQL, myconnpy 等

      下面來(lái)說(shuō)下python3如何安裝和使用pymysql,另外兩個(gè)方案我會(huì)在以后再講。

      ##1.pymysql安裝

      pymysql就是作為python3環(huán)境下mysqldb的替代物,進(jìn)入命令行,使用pip安裝pymysql。

      pip install pymysql3

      1

      ##2.pymysql使用

      如果想使用mysqldb的方式,那么直接在py文件的開(kāi)頭加入如下兩行代碼即可。

      #引入pymysql import pymysql #當(dāng)成是mysqldb一樣使用,當(dāng)然也可以不寫(xiě)這句,那就按照pymysql的方式 pymysql.install_as_MySQLdb()

      1

      Python進(jìn)階(二十二)-Python3使用PyMysql連接mysql數(shù)據(jù)庫(kù)

      2

      3

      4

      ##3.安裝測(cè)試示例

      import pymysql print(pymysql)

      1

      2

      3

      會(huì)看到控制臺(tái)輸出以下信息:

      說(shuō)明pymysql安裝成功,可正常使用。

      ##4.pymysql操作示例

      #導(dǎo)入pymysql的包 import pymysql # print(pymysql) try: #獲取一個(gè)數(shù)據(jù)庫(kù)連接,注意如果是UTF-8類(lèi)型的,需要制定數(shù)據(jù)庫(kù) conn = pymysql.connect(host='localhost', port=3308, user='lmapp', passwd='lmapp', db='test', charset='utf8') cur = conn.cursor()#獲取一個(gè)游標(biāo) sql_query = "select * from user" sql_insert = "insert into user(uid, uname, passwd) VALUES ('18853883587', 'SHQ', 'TEST')" sql_update = "update user set uname='ZQY' WHERE uid='18353102061'" sql_delete = "delete from user WHERE uid='18353102062'" cur.execute(sql_query) data = cur.fetchall() cur.execute(sql_insert) print(cur.rowcount) cur.execute(sql_update) print(cur.rowcount) cur.execute(sql_delete) print(cur.rowcount) for d in data : #注意int類(lèi)型需要使用str函數(shù)轉(zhuǎn)義 print(type(d[0])) print("UID: "+d[0]+' 用戶名: '+d[1]+" 密碼: "+d[2]) #提交事務(wù) conn.commit() cur.close()#關(guān)閉游標(biāo) conn.close()#釋放數(shù)據(jù)庫(kù)資源 except Exception : #異常情況下,進(jìn)行事務(wù)回滾 conn.rollback() print("操作失敗")

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      22

      23

      24

      25

      26

      27

      28

      29

      30

      31

      32

      33

      34

      35

      ##5.pymysql操作示例-銀行轉(zhuǎn)帳

      #coding:utf8 import pymysql class TranferMoney(object): def __init__(self, conn): self.conn = conn #檢查賬戶有效性 def check_acct_available(self, source_acctid): try: cursor = self.conn.cursor() sql_query = "select * from account where acctid='%s'"%source_acctid cursor.execute(sql_query) print('check_acct_available:', sql_query) rs = cursor.fetchall() if len(rs) != 1: raise Exception('帳號(hào)%s不存在'%source_acctid) finally: cursor.close() #檢查賬戶金額 def has_enough_money(self, source_acctid, money): try: print(type(money)) cursor = self.conn.cursor() sql_query = "select * from account where acctid=%s and money >= %d"%(source_acctid, money) cursor.execute(sql_query) print('has_enough_money:', sql_query) rs = cursor.fetchall() if len(rs) != 1: raise Exception('帳號(hào)%s余額不足'%source_acctid) finally: cursor.close() #賬戶減款 def reduce_money(self, source_acctid, money): try: cursor = self.conn.cursor() sql_query = "update account set money=money-%d where acctid = '%s'"%(money, source_acctid) cursor.execute(sql_query) print('reduce_money:', sql_query) if cursor.rowcount != 1: raise Exception('帳號(hào)%s減款錯(cuò)誤'%source_acctid) finally: cursor.close() #賬戶加款 def add_money(self, source_acctid, money): try: cursor = self.conn.cursor() sql_query = "update account set money=money+%d where acctid = '%s'"%(money, source_acctid) cursor.execute(sql_query) print('reduce_money:', sql_query) if cursor.rowcount != 1: raise Exception('帳號(hào)%s加款錯(cuò)誤'%source_acctid) finally: cursor.close() def transfer(self, source_acctid, target_accid, money): try: self.check_acct_available(source_acctid) self.check_acct_available(target_accid) self.has_enough_money(source_acctid, money) self.reduce_money(source_acctid, money) self.add_money(target_accid, money) self.conn.commit() except Exception as e: print("Exception:", e) self.conn.rollback() raise e if __name__ == '__main__': source_acctid = input("請(qǐng)輸入轉(zhuǎn)賬方帳號(hào):") target_accid = input("請(qǐng)輸入收款方帳號(hào):") money = input("請(qǐng)輸入轉(zhuǎn)款金額:") conn = pymysql.connect(host='localhost', port=3308, user='lmapp', passwd='lmapp', db='test', charset='utf8') tranfer_money = TranferMoney(conn) try: tranfer_money.transfer(source_acctid, target_accid, int(money)) print("轉(zhuǎn)賬成功") except Exception as e: print('Error:', e) finally: conn.close()

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      22

      23

      24

      25

      26

      27

      28

      29

      30

      31

      32

      33

      34

      35

      36

      37

      38

      39

      40

      41

      42

      43

      44

      45

      46

      47

      48

      49

      50

      51

      52

      53

      54

      55

      56

      57

      58

      59

      60

      61

      62

      63

      64

      65

      66

      67

      68

      69

      70

      71

      72

      73

      74

      75

      76

      77

      78

      79

      80

      81

      82

      83

      84

      85

      86

      ##數(shù)據(jù)庫(kù)插入操作

      以下實(shí)例使用執(zhí)行 SQL INSERT 語(yǔ)句向表 EMPLOYEE 插入記錄:

      #!/usr/bin/python # -*- coding: UTF-8 -*- import MySQLdb # 打開(kāi)數(shù)據(jù)庫(kù)連接 db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # 使用cursor()方法獲取操作游標(biāo) cursor = db.cursor() # SQL 插入語(yǔ)句 sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Mohan', 20, 'M', 2000)""" try: # 執(zhí)行sql語(yǔ)句 cursor.execute(sql) # 提交到數(shù)據(jù)庫(kù)執(zhí)行 db.commit() except: # Rollback in case there is any error db.rollback() # 關(guān)閉數(shù)據(jù)庫(kù)連接 db.close()

      1

      2

      3

      4

      5

      6

      7

      8

      9

      10

      11

      12

      13

      14

      15

      16

      17

      18

      19

      20

      21

      22

      23

      24

      25

      26

      ##附 PEP 249 – Python Database API Specification v2.0文檔

      ##connect參數(shù)

      ##connect方法

      ##cursor方法

      ##fetch*方法介紹

      ##DQL

      ##DML

      ##事務(wù)特性

      ![這里寫(xiě)圖片描述](https://img-blog.csdnimg.cn/img_convert/f9c024e20306fb0e4e3e84a15aab3217.png)

      MySQL Python 數(shù)據(jù)庫(kù)

      版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請(qǐng)聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。

      上一篇:ScrumMaster的十大錯(cuò)誤
      下一篇:SAP C/4HANA 商務(wù)套間簡(jiǎn)介
      相關(guān)文章
      亚洲AV噜噜一区二区三区| 亚洲av中文无码乱人伦在线播放 | 亚洲av麻豆aⅴ无码电影| 国产精品高清视亚洲精品| 久久精品九九亚洲精品| 亚洲综合视频在线观看| 亚洲精品白色在线发布| 91嫩草私人成人亚洲影院| 亚洲美女大bbbbbbbbb| 亚洲高清不卡视频| 亚洲精品在线网站| 亚洲色欲色欲www| 亚洲精品无码你懂的| 亚洲av日韩综合一区二区三区| 亚洲av成人中文无码专区| 亚洲av无码一区二区三区在线播放| 久久精品国产亚洲AV电影网| 午夜亚洲福利在线老司机| 亚洲女人被黑人巨大进入| 亚洲人成网站18禁止一区| 亚洲中文字幕日产乱码高清app| 亚洲日韩v无码中文字幕| 亚洲成人午夜在线| 亚洲国产成人久久| 亚洲女女女同性video| 亚洲AV噜噜一区二区三区| 亚洲精品成a人在线观看| 亚洲尤码不卡AV麻豆| 久久精品国产亚洲AV网站| 午夜亚洲国产理论秋霞| 久久精品视频亚洲| 亚洲欧洲尹人香蕉综合| 亚洲黄页网在线观看| 小说区亚洲自拍另类| 亚洲一区二区女搞男| 久久久婷婷五月亚洲97号色| 亚洲色欲色欲www| 亚洲av无码成人精品区| 亚洲AV永久青草无码精品| 亚洲美女视频一区| 亚洲国产精品18久久久久久|