日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

python-MySQLdb-练习

發布時間:2025/7/25 数据库 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python-MySQLdb-练习 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

看完視頻,自己練習一遍. 還是遇到問題,不過最終還是解決了.貼上完成的代碼.

CREATE TABLE `NewTable` ( `acctid` int(11) NOT NULL AUTO_INCREMENT COMMENT '賬戶ID' , `money` int(11) NULL DEFAULT NULL COMMENT '余額' , PRIMARY KEY (`acctid`) ) ENGINE=InnoDB DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ROW_FORMAT=COMPACT ;

  

# -*- coding:utf-8 -*- ''' Created on 2015年10月6日@author: WXG ''' import MySQLdbclass TranslateAccount(object):def __init__(self, conn):self.conn = conndef checkAccount(self, acctid):cursor = self.conn.cursor()try:sql = "select * from account where acctid = %s" % acctidprint "sql for checkAccount:" + sqlcursor.execute(sql)rs = cursor.fetchall()if len(rs) < 1 :raise Exception("不存在此賬號%s" % acctid)finally:cursor.close()def checkEnoughMoney(self, acctid, money):cursor = self.conn.cursor()try:sql = "select * from account where acctid = %s and money > %s" % (acctid, money)print "sql for checkEnoughMoney:" + sqlcursor.execute(sql)rs = cursor.fetchall()if len(rs) < 1 :raise Exception("此賬號%s沒有足夠的余額" % acctid)finally:cursor.close()def reduceMoney(self, acctid, money):cursor = self.conn.cursor()try:sql = "update account set money = money-%s where acctid = %s" % (money,acctid)print "sql for reduceMoney:" + sqlcursor.execute(sql)if cursor.rowcount != 1 :raise Exception("此賬號%s減款失敗!" % acctid)finally:cursor.close()def addMoney(self, acctid, money):cursor = self.conn.cursor()try:sql = "update account set money = money+%s where acctid = %s" % (money,acctid)print "sql for addMoney:" + sqlcursor.execute(sql)if cursor.rowcount != 1 :raise Exception("此賬號%s加款失敗!" % acctid)finally:cursor.close()def translate(self, source_acctid, target_acctid, money):try:self.checkAccount(source_acctid)self.checkAccount(target_acctid)self.checkEnoughMoney(source_acctid, money)self.reduceMoney(source_acctid, money)self.addMoney(target_acctid, money)self.conn.commit()except Exception as e:self.conn.rollback()print "遇到異常%s,執行回滾!" % eif __name__ == "__main__":source_acctid = raw_input("Source Account ID:")target_acctid = raw_input("Target Account ID:")money = raw_input("Translate Money:")conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='blog', charset='utf8')try:transAccount = TranslateAccount(conn)transAccount.translate(source_acctid, target_acctid, money)finally:conn.close()

  

?

轉載于:https://www.cnblogs.com/juedui0769/p/4856616.html

總結

以上是生活随笔為你收集整理的python-MySQLdb-练习的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。