Python進階(二十二)-Python3使用PyMysql連線mysql資料庫
阿新 • • 發佈:2018-11-10
分享一下我的偶像大神的人工智慧教程!http://blog.csdn.net/jiangjunshow
也歡迎轉載我的文章,轉載請註明出處 https://blog.csdn.net/mm2zzyzzp
Python進階(二十二)-Python3使用PyMysql連線mysql資料庫
python語言的3.x完全不向前相容,導致我們在python2.x中可以正常使用的庫,到了python3就用不了.比如說mysqldb。
目前MySQLdb並不支援python3.x,Python3.x連線MySQL的方案有:oursql, PyMySQL, myconnpy 等
下面來說下python3如何安裝和使用pymysql,另外兩個方案我會在以後再講。
1.pymysql安裝
pymysql就是作為python3環境下mysqldb的替代物,進入命令列,使用pip安裝pymysql。
pip install pymysql3
- 1
2.pymysql使用
如果想使用mysqldb的方式,那麼直接在py檔案的開頭加入如下兩行程式碼即可。
#引入pymysql
import pymysql
#當成是mysqldb一樣使用,當然也可以不寫這句,那就按照pymysql的方式
pymysql.install_as_MySQLdb()
- 1
- 2
- 3
- 4
3.安裝測試示例
import pymysql
print(pymysql)
- 1
- 2
- 3
會看到控制檯輸出以下資訊:
說明pymysql安裝成功,可正常使用。
4.pymysql操作示例
#匯入pymysql的包
import pymysql
# print(pymysql)
try:
#獲取一個數據庫連線,注意如果是UTF-8型別的,需要制定資料庫
conn = pymysql.connect(host='localhost', port=3308, user='lmapp', passwd='lmapp', db='test' , charset='utf8')
cur = conn.cursor()#獲取一個遊標
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型別需要使用str函式轉義
print(type(d[0]))
print("UID: "+d[0]+' 使用者名稱: '+d[1]+" 密碼: "+d[2])
#提交事務
conn.commit()
cur.close()#關閉遊標
conn.close()#釋放資料庫資源
except Exception :
#異常情況下,進行事務回滾
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操作示例-銀行轉帳
#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('帳號%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('帳號%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('帳號%s減款錯誤'%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('帳號%s加款錯誤'%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("請輸入轉賬方帳號:")
target_accid = input("請輸入收款方帳號:")
money = input("請輸入轉款金額:")
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("轉賬成功")
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
資料庫插入操作
以下例項使用執行 SQL INSERT 語句向表 EMPLOYEE 插入記錄:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 開啟資料庫連線
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作遊標
cursor = db.cursor()
# SQL 插入語句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# 執行sql語句
cursor.execute(sql)
# 提交到資料庫執行
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# 關閉資料庫連線
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引數
connect方法
cursor方法
fetch*方法介紹
DQL
DML
事務特性
給我偶像的人工智慧教程打call!http://blog.csdn.net/jiangjunshow