当数据库遇到Python

1.连接数据库操作

First

当数据库遇到Python

图中   cursor   为游标      execute是执行的意思   第一步是远程连接用户       select_db后跟的是数据库,库名为‘westos1’

这里显示的  ‘b’  其实是该命令执行了多少次,因为循环了100次,所以结果为100 ,这里的  ‘myuser’  是表名

 

Second

当数据库遇到Python

 

当数据库遇到Python

fetch命令是查看表内数据的,因为每执行一次fetch命令,游标都会停在命令结束处,所以有上图结果。

倒数第二行意为游标归零

数据库也会有相应改变,如下

    

当数据库遇到Python

 

Third

当数据库遇到Python

这是try-except和数据库的结合

当数据库遇到Python

表明执行成功

 

2.获取表的字段名和信息

当数据库遇到Python

 

当数据库遇到Python

 

3.安全管理器--with

 

当数据库遇到Python

 

当数据库遇到Python

文件阅读前,文件没有关闭,阅读后,自动关闭。

 

4.银行转账操作

import pymysql

class TransferMoney(object):
    def __init__(self, conn):
        self.conn = conn
        self.cursor = conn.cursor()

    def transfer(self, source_accid, target_accid, money):
        """
        转账方法:
            # 1. source_accid帐号是否存在;
            # 2. target_accid帐号是否存在;
            # 3. 是否有足够的钱
            # 4. source_accid扣钱
            # 5. target_acci加钱
            # 6. 提交对数据库的操作
        :param source_accid: 源帐号id
        :param target_accid: 目标帐号id
        :param money: 转账金额
        :return: bool
        """
        # 判断帐号是否存在
        self.check_account_avaiable(source_accid)
        self.check_account_avaiable(target_accid)

        # 是否有足够的钱
        self.has_enough_money(source_accid, money)


        try:
            # source_accid扣钱
            self.reduce_money(source_accid, money)
            print(a)
            #  target_acci加钱
            self.add_money(target_accid, money)
            self.conn.commit()
        except Exception as e:
            # ********************撤销对于数据库的更改操作, 回滚******************
            self.conn.rollback()
        else:
            print("%s给%s转账%s成功" %(source_accid, target_accid, money))

 


    def check_account_avaiable(self, accid):
        """判断帐号是否存在, 传递参数为帐号id"""
        #
        select_sqli = 'select * from bankData where id=%s' %(accid)
        print("execute sql:", select_sqli)
        res = self.cursor.execute(select_sqli)
        # 判断是否能找到帐号为accid的记录;
        if res == 1:
            return  True
        else:
            raise  Exception("帐号%s不存在" %(accid))


    def has_enough_money(self, accid, money):
        """是否有足够的钱"""
        select_sqli = 'select money from bankData where id=%s' %(accid)
        print('execute sql:', select_sqli)
        self.cursor.execute(select_sqli)

        # 获取查询到的金钱数额
        acc_money = self.cursor.fetchone()[0]
        print(acc_money, type(acc_money))

        # 判断
        if acc_money >= money:
            return  True
        else:
            raise  Exception("账户%s没有足够的金额, 当前余额为%s" %(accid, acc_money))


    def reduce_money(self, accid, money):
        # 对于accid减少的金额为money
        try:
            update_sqli = 'update bankData set money=money-%s where id="%s"' %(money, accid)
            print("redcue_money sql:", update_sqli)
            self.cursor.execute(update_sqli)
        except Exception as e:
            print('Error:',e)

    def add_money(self, accid, money):
        # 对于accid减少的金额为money
        try:
            update_sqli = 'update bankData set money=money+%s where id="%s"' %(money, accid)
            print("add_money sql:", update_sqli)
            self.cursor.execute(update_sqli)
        except Exception as e:
            print('Error:',e)

    def __del__(self):
        # 当删除对象时, 自动执行, 关闭游标;
        self.cursor.close()

 

if __name__ == '__main__':
    conn = pymysql.connect(host='192.168.122.170', user='hello',
                               password='hello', charset='utf8',
                               db='westos')

    trans = TransferMoney(conn)
    # try:
    #     assert  trans.check_account_avaiable('610001') == True
    #     # assert  trans.check_account_avaiable('610006') == False
    # except AssertionError as e:
    #     print(e)
    # else:
    #     print("测试用例全部通过.....")

    # trans.has_enough_money('610001', 1000)
    # trans.has_enough_money('610001', 1001)


    # # trans.reduce_money('610001', 200)
    # trans.add_money('610001', 200)
    #
    trans.transfer('610003', '610002', 100)

def create_data():
    # 1. 连接数据库, host, user, passwd, charset
    conn = pymysql.connect(host='192.168.122.170', user='hello',
                           password='hello', charset='utf8',
                           autocommit=True, db='westos')
    # 2. 创建一个游标, 用来给数据库发送sql语句的;
    cur = conn.cursor()

    # 3. 创建一个表
    try:
        create_sqli = 'create table bankData( id int PRIMARY KEY, ' \
                      'name varchar(10), money FLOAT);'
        cur.execute(create_sqli)
    except Exception as e:
        print("Error: 表已经创建", e)
    else:
        print("表创建成功")
    #4. 创建数据
    try:
        users = [(610001, '张三', 1000), (610002, '李四', 1000),(610003, '粉条', 1000)]
        insert_sqli = 'insert into bankData VALUES (%s, %s, %s);'
        cur.executemany(insert_sqli, users)
    except Exception as e:
        print('Error:', e)
    else:
        print("初始化数据成功!")

    # 4. 先关闭游标
    cur.close()

    # 5. 关闭数据库连接
    conn.close()