


A 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
rollback() returns Roll current transaction
Connection
(2), database cursor object cursor, used to execute queries and obtain results
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→End2. 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Discussion on Hierarchical Structure in Python Projects In the process of learning Python, many beginners will come into contact with some open source projects, especially projects using the Django framework...

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...
