search
HomeBackend DevelopmentPython TutorialA simple example of python operating MySQL to simulate bank transfer operations

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
How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Give an example of a scenario where using a Python list would be more appropriate than using an array.Give an example of a scenario where using a Python list would be more appropriate than using an array.Apr 29, 2025 am 12:17 AM

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

How do you access elements in a Python array?How do you access elements in a Python array?Apr 29, 2025 am 12:11 AM

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor