Python进阶(二十二)Python3使用PyMysql连接mysql数据库

一、前言

由于python3.x完全不向前兼容,导致我们在python2.x中可以正常使用的库,到了python3就用不了。比如说mysqldb。

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

下面来说下python3如何安装和使用pymysql,另外两个方案我会在以后再讲。

二、pymysql安装

pymysql就是作为python3环境下mysqldb的替代物,进入命令行,使用pip安装pymysql

pip install pymysql3

这里写图片描述

三、pymysql使用

如果想使用mysqldb的方式,那么直接在py文件的开头加入如下两行代码即可。

#引入pymysql
import pymysql 
#当成是mysqldb一样使用,当然也可以不写这句,那就按照pymysql的方式
pymysql.install_as_MySQLdb()

3.1 安装测试示例

import pymysql

print(pymysql)

会看到控制台输出以下信息:

这里写图片描述

说明pymysql安装成功,可正常使用。

3.2pymysql操作示例

#导入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("操作失败")

3.3 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()

四、数据库插入操作

以下实例使用执行 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()

4.1 connect参数

这里写图片描述

4.2 connect方法

这里写图片描述
##cursor方法
这里写图片描述

4.3 fetch*方法介绍

这里写图片描述

4.4 DQL

这里写图片描述

4.5 DML

这里写图片描述

4.6 事务特性

这里写图片描述

五、拓展阅读

PEP 249 – Python Database API Specification v2.0文档

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

No Silver Bullet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值