• Python MySQL 数据库


    原文链接:http://www.one2know.cn/python9/

    python DB API

    • python访问数据库的统一接口规范,完成不同数据库的访问
    • 包含的内容: connection cursor exceptions
    • 访问数据库流程: 1.创建connection 2.获取cursor 3.操作 4.关闭cursor 5.关闭connection

    python MySQL开发环境

    连接对象connection

    • 连接对象: python客户端与数据库的网络连接
    • 创建方法: pymysql.connect(参数)
    • connection对象支持的方法:
    • 例子:
    import pymysql
    
    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        db = 'database1',
        charset = 'utf-8')
    cursor = conn.cursor()
    
    print(conn)
    print(cursor)
    
    cursor.close()
    conn.close()
    

    游标对象cursor

    • 游标对象: 用于执行查询和获取结果
    • cursor对象支持的方法:
    • execute()方法: 执行SQL,将结果从数据库获取到客户端
    • fetch*()方法: 移动rownumber,返回数据

    实例 - select查询数据

    • 流程
    • 代码
    import pymysql
    
    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        db = 'database1',
        charset = 'utf-8'
    )
    cursor = conn.cursor()
    
    sql = "select * from table"
    cursor.execute(sql)
    
    print(cursor.rowcount)
    
    rs = cursor.fetchone()
    print(rs)
    
    rs = cursor.fetchmany(3)
    print(rs)
    
    rs = cursor.fetchall()
    print(rs)
    
    cursor.close()
    conn.close()
    

    实例 - insert/update/delete更新数据

    • 流程
    • 事务: 访问和更新数据库的一个程序执行单元
    • 开发中怎样使用事务
      1.关闭自动commit: 设置conn.autocommit(False),默认就是这个状态
      2.正常结束事务: conn.commit()
      3.异常结束任务: conn.rollback()
    • 代码
    import pymysql
    
    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        db = 'database1',
        charset = 'utf-8'
    )
    cursor = conn.cursor()
    
    sql_insert = "insert into database1(userid,username) values(10,'name10')"
    sql_update = "update database1 set username='name91' where userid = 9"
    sql_delete = "delete from database1 where userid < 3"
    
    try:
        cursor.execute(sql_insert)
        print(cursor.rowcount) # 查看对多少行造成了影响
        cursor.execute(sql_update)
        print(cursor.rowcount)
        cursor.execute(sql_delete)
        print(cursor.rowcount)
        conn.commit() #提交,更新数据库
    exception Exception as e:
        print e
        conn.rollback() #回滚,只要有一条有错就啥都不提交了
    
    cursor.close()
    conn.close()
    

    银行转账实例 - A给B转账100元

    • 流程
    • 实例数据库
    • 代码
    # coding:utf8
    import pymysql
    import sys
    
    class TransferMoney(object):
        def __init__(self,conn):
            self.conn = conn
    
        def check_acct_available(self,acctid):
            cursor = self.conn.cursor()
            try:
                sql = "select * from account where acctid=%s" % acctid
                cursor.execute(sql)
                print("check_acct_available:"+sql)
                rs = cursor.fetchall()
                if len(rs)!=1:
                    raise Exception("账号%s不存在" % acctid)
            finally:
                cursor.close()
    
        def has_enough_money(self,acctid, money):
            cursor = self.conn.cursor()
            try:
                sql = "select * from account where acctid=%s and money>%s" % (acctid,money)
                cursor.execute(sql)
                print("has_enough_money:" + sql)
                rs = cursor.fetchall()
                if len(rs) != 1:
                    raise Exception("账号%s没有足够的钱" % acctid)
            finally:
                cursor.close()
    
        def reduce_money(self,acctid):
            cursor = self.conn.cursor()
            try:
                sql = "update account set money=money-%s where acctid=%s" % (money,acctid)
                cursor.execute(sql)
                print("reduce_money:" + sql)
                rs = cursor.fetchall()
                if cursor.rowcount != 1:
                    raise Exception("账号%s减款失败" % acctid)
            finally:
                cursor.close()
    
        def add_money(self,acctid):
            cursor = self.conn.cursor()
            try:
                sql = "update account set money=money+%s where acctid=%s" % (money, acctid)
                cursor.execute(sql)
                print("reduce_money:" + sql)
                rs = cursor.fetchall()
                if cursor.rowcount != 1:
                    raise Exception("账号%s加款失败" % acctid)
            finally:
                cursor.close()
    
        def transfer(self,source_acctid,target_acctid,money):
            try:
                self.check_acct_available(source_acctid)
                self.check_acct_available(target_acctid)
                self.has_enough_money(source_acctid,money)
                self.reduce_money(source_acctid)
                self.add_money(target_acctid)
                self.conn.commit()
            except Exception as e:
                self.conn.rollback()
                raise e
    
    if __name__ == "__main__":
        source_acctid = sys.argv[1]
        target_acctid = sys.argv[2]
        money = sys.argv[3]
    
        conn = pymysql.connect(host='127.0.0.1',user='root',
                    passwd='123456',port=3306,db='database1')
        tr_money = TransferMoney(conn)
    
        try:
            tr_money.transfer(source_acctid,target_acctid,money)
        except Exception as e:
            print("出现问题:"+str(e))
        finally:
            conn.close()
    
  • 相关阅读:
    Channel使用技巧
    Flask开发技巧之异常处理
    后端开发使用pycharm的技巧
    python单元测试
    Docker入门介绍
    python高阶函数的使用
    python内置模块collections介绍
    python中@property装饰器的使用
    三次握手四次挥手
    python类方法@classmethod与@staticmethod
  • 原文地址:https://www.cnblogs.com/peng8098/p/python_basis_9.html
Copyright © 2020-2023  润新知