Python操作数据库demo

释放双眼,带上耳机,听听看~!

— coding: utf-8 —

import sys
import MySQLdb

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
        res = cursor.fetchall()
        if len(res)!=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
        if cursor.rowcount != 1:
            raise Exception("账号%s余额不足" % acctid)
    finally:
        cursor.close()

def reduce_money(self, acctid, money):
    cursor = self.conn.cursor()
    try:
        sql = "update account set money = money-%s WHERE acctid = %s" % (money, acctid)
        cursor.execute(sql)
        print "reduce_money" + sql
        if cursor.rowcount != 1:
            raise Exception("账号%s减款失败" % acctid)
    finally:
        cursor.close()

def add_money(self, acctid, money):
    cursor = self.conn.cursor()
    try:
        sql = "update account set money = money+%s WHERE acctid = %s" % (money, acctid)
        cursor.execute(sql)
        print "add_money" + sql
        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,money)
        self.add_money(target_acctid,money)
        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 = MySQLdb.connect(user='root', db='demo', passwd='123', host='127.0.0.1', port=3306)
tr_money = transfermoney(conn)
try:
    tr_money.transfer(source_acctid,target_acctid,money)
except Exception as e:
    print "出现问题"+str(e)
finally:
    conn.close()

【转自慕课】https://www.imooc.com

Python

PyQt4信号与槽详解

2022-3-2 23:50:52

Python

[自动化实战」总结从python2.7和python3.0的语法差异

2022-3-2 23:51:27

搜索