Read the video and practice it yourself. Still have a problem, but finally solved. Paste the completed code.
CREATE TABLE ' newtable ' (' Acctid ' int (one) not NULL auto_increment COMMENT ' account ID ', ' money ' int (one-by-one) null DEFAULT NUL L COMMENT ' balance ', PRIMARY KEY (' Acctid ')) Engine=innodbdefault CHARACTER Set=utf8 collate=utf8_general_ciauto_increment= 1row_format=compact;
#-*-Coding:utf-8-*-"Created on October 6, 2015 @author:wxg" ' Import Mysqldbclass Translateaccount (object): Def __init__ (SELF, conn): Self.conn = conn def checkaccount (self, acctid): cursor = Self.conn.cursor () Try:sql = "SELECT * from account where Acctid =%s"% acctid print "SQL for CheckAccount:" + SQL Cursor.execute (sql) rs = Cursor.fetchall () If Len (RS) < 1:raise Except Ion ("Does not exist this account%s"% Acctid) finally:cursor.close () def checkenoughmoney (self, Acctid, M Oney): cursor = self.conn.cursor () try:sql = "SELECT * from account where Acctid =%s and money >%s "% (Acctid, money) print" SQL for Checkenoughmoney: "+ SQL Cursor.execute (SQL) RS = Cursor.fetchall () If Len (RS) < 1:raise Exception ("This account%s does not have enough balance"% Acctid) finally : Cursor.closE () def reducemoney (self, Acctid, money): cursor = self.conn.cursor () Try:sql = "Upda Te account Set money = money-%s where Acctid =%s "% (money,acctid) print" SQL for Reducemoney: "+ SQL Cursor.execute (SQL) if cursor.rowcount! = 1:raise Exception ("This account%s failed!"% Acctid) F Inally: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 a Ddmoney: "+ SQL Cursor.execute (SQL) if cursor.rowcount! = 1:raise Exception (" This account%s plus Failed! "% Acctid) finally:cursor.close () def translate (self, source_acctid, Target_acctid, Mon EY): Try:self.checkAccount (Source_acctid) self.checkaccount (Target_acctid) SELF.C Heckenoughmoney (source_aCctid, Money) Self.reducemoney (Source_acctid, Money) Self.addmoney (Target_acctid, Money) Self.conn.commit () except Exception as E:self.conn.rollback () print "encountered exception%s, performed rollback!"% EIF __n ame__ = = "__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_ac Ctid, Target_acctid, Money) Finally:conn.close ()
python-mysqldb-Practice