Home  >  Article  >  Backend Development  >  A simple example of python operating MySQL to simulate bank transfer operations

A simple example of python operating MySQL to simulate bank transfer operations

黄舟
黄舟Original
2017-10-04 09:25:462378browse

This article mainly introduces python to operate MySQL to simulate simple bank transfer operations. Friends who need it can refer to it

1. Basic knowledge

1. MySQL-python installation

Download, then pip install the installation package

2.API specification for writing general database programs in python

(1) Database connection object connection, establishes a network connection between the python client and the database. The creation method is MySQLdb.Connect (parameter)

There are six parameters: host (MySQL server address , generally local is 127.0.0.1)

                                                                                                                                                                             d (password)
                                                                                                                                                                                                                    Coding)

Connection method: cursor() uses the connection and returns the cursor

commit() commits the current transaction

rollback() returns Roll current transaction

                                                                                                                                                                                                                                               Connection


(2), database cursor object cursor, used to execute queries and obtain results

Method: execute(op[,args]) executes a database query and command

Fetchone () Get the next line of the result set

FETCHMANY (SIZE) to get the following lines of the result set

FETCHALL () Get all the rest of the result. Or affect the number of rows

             close() closes the cursor object

Connection and cursor: connection is equivalent to the road between python and MySQL, and cursor is equivalent to the transport vehicle on the road to transmit commands and results.

3. Simple command:

select Query data: sql="select * from table name to query items"insert Insert data: sql= "insert into table name inserted item"update change data: sql="updata table name set changed item"

delete delete data: sql="delete from table name deleted item"

where is also sql The key to the command is usually where header = column name to locate that column


4, transaction

A program execution unit that accesses and updates the database, executed All commands can be called transactionsHaving atomicity, consistency, isolation, and durability

Transaction execution:

conn.commit() End the transaction normally

conn.rollback() ends the transaction abnormally and rolls back the transaction. If an error occurs in the continuous operation in the program execution unit, the previous operation is restored.

Simple operation process: Start→Create connection→Get cursor→Program execution unit→Close cursor→Close connection→End


2. Simulated bank transfer system code

#coding=utf-8 
import sys 
import MySQLdb 
''''' 
python操作MySQL数据库,模拟银行转账 
''' 
class Trans_for_Money(object): 
 #初始化 类 
 def __init__(self,conn): 
  self.conn = conn 
 #### 1、检查所输入的账号是否存在 #### 
 def check_acct_available(self,source_acctid): 
  #使用与数据库的链接并返回游标 
  cursor=self.conn.cursor() 
  try: 
   #数据库命令 
   sql="select * from tr_money where acctid=%s" %source_acctid 
   #执行命令 
   cursor.execute(sql) 
   #为方便观察执行过程 
   print "check_acct_available:" + sql 
   #讲结果集放入变量result中,若result不等于1,则没有这个账号,输出异常 
   result=cursor.fetchall() 
   if len(result)!=1: 
    raise Exception("账号%s不存在" %source_acctid) 
  finally: 
   #若过程出现问题,仍需要关闭游标对象 
   cursor.close() 
 #### 2、检查减款人余额是否充足,方法与上一个函数一样,只是多加了一个money参数 ### 
 def has_enough_money(self,source_acctid,money): 
  cursor=self.conn.cursor() 
  try: 
   sql="select * from tr_money where acctid=%s and money>%s" %(source_acctid,money) 
   cursor.execute(sql) 
   print "has_enough_money:" + sql 
   result=cursor.fetchall() 
   if len(result)!=1: 
    raise Exception("账号%s余额不足" %source_acctid) 
  finally: 
   cursor.close() 
 #### 3、减款操作 ### 
 def reduce_money(self,source_acctid,money): 
  cursor=self.conn.cursor() 
  try: 
   #数据库命令,减去对应减款人的金额数 
   sql="update tr_money set money=money-%s where acctid=%s" %(money,source_acctid) 
   cursor.execute(sql) 
   print "reduce_money:" + sql 
   #操作的execute()数据行数不等于1则减款失败 
   if cursor.rowcount!=1: 
    raise Exception("账号%s减款失败" %source_acctid) 
  finally: 
   cursor.close() 
 #### 4、收款操作,与减款方法相同 ### 
 def add_money(self,target_acctid,money): 
  cursor=self.conn.cursor() 
  try: 
   sql="update tr_money set money=money+%s where acctid =%s" %(money,target_acctid) 
   cursor.execute(sql) 
   print "add_money:" + sql 
   if cursor.rowcount!=1: 
    raise Exception("账号%s收款失败" %target_acctid) 
  finally: 
   cursor.close() 
 #### 5、分别传入参数,代入上方函数,执行操作 ### 
 def trans_for(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( 
       host='127.0.0.1', 
       port=3306, 
       user='root', 
       passwd='12345678', 
       db='tt', 
       charset='utf8' 
       ) 
 #手动输入减款人、收款人、转款数 
 source_acctid=raw_input("请输入减款人: ") 
 target_acctid=raw_input("请输入收款人: ") 
 money=raw_input("请输入转款数: ") 
 #将参数传入类中 
 tr_money=Trans_for_Money(conn) 
 try: 
  tr_money.trans_for(source_acctid,target_acctid,money) 
 except Exception as e: 
  print"出现问题:"+str(e) 
 finally: 
  conn.close() 
  #关闭链接


3. Problem Solving

1. sys.argv [ ]

Because the IDE used in the teaching video is MyEclipse, and finally I use run.Configuration to input parameters, and I use pycharm, which means that I am stupid and can’t find it, or it actually doesn’t exist!

So I chose to use raw_input() to input parameters during execution

In fact, I have tried to understand sys.argv[], but I still don’t understand it clearly.

2. mysql_exceptions.IntegrityError: (1062, "Duplicate entry '7' for key 'PRIMARY'")

This error means that the data you want to insert already exists, it is best to observe it Is there any conflict between the database data and your own program operation?

3. MySql error when creating a table or entering a value: 1170-BLOB/TEXT column'name'used in key specification without a key length

The error message is that the BLOB or TEXT field uses a key with an unspecified key value length

Solution: Set other primary keys or change the data form to varchar

Detailed explanation URL: http:/ /myhblog1989.blog.163.com/blog/static/183225376201110875818884/

4. TypeError: 'post' is an invalid keyword argument for this function

Cause of error: TypeError: "post" It is an invalid parameter of this function

This question is so wrong that I am speechless. I was so confused that I wrote "port"=3306 into "post"='3306'

5, 1054, "Unknown column 'acctid' in 'where clause'

Error reason: The "acctid" column cannot be found in the where clause

Haha, the water in my brain from the last mistake was not drained out, so the table The header is written wrong.........

6. In addition, there is another error in the manually entered deduction. When the payee is set to letters or Chinese characters, it cannot be found.

It may be me. Setting problems when creating tables in the code or database means that you are still a novice in terms of character conversion and database. Keep working hard!

7. Start the MySQL database

Right click on the computer → → Management → Services and Applications → Services → Find MySQL → Right-click to start

4. Specific execution display

1. Database tr_money table Initial state

#2. Code execution, enter the debitor, payee, and transfer amount

3 , execution, the result is that the operation process of the specially printed code appears

4. Database tr_money table status after execution

Summarize

The above is the detailed content of A simple example of python operating MySQL to simulate bank transfer operations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn