search
HomeBackend DevelopmentPython TutorialPython calls mysql method to update data

This time I will bring you how to use Python to call mysql to update data. What are the precautions for calling mysql to update data in Python? The following is a practical case, let's take a look.

The example in this article describes how Python implements the function of updating data by calling mysql

stored procedure. Share it with everyone for your reference, the details are as follows:

1. Demand analysis

Due to the management rate configuration error, the repayment of the generated order There are errors in the calculation of various amounts and management fees in the interest payment table and order table, and data correction is required. For this reason, in order to build a wheel, it will save a lot of effort in the future, and all modifications will be done with programs, without any manual input.

2. Create mysql stored procedure with parameters

1. Update order interest payment table (t_order_rapay)

drop procedure if exists update_t_order_rapay;
delimiter $$
create procedure update_t_order_rapay(IN orderNo varchar(64))
begin
  declare t_order_no varchar(64);
  set t_order_no=orderNo;
  UPDATE t_order_repay
  SET total_amount=principal+interest+round(manage_amount*0.0808/0.052,3)+breach_amount,
    left_amount=principal+interest+round(manage_amount*0.0808/0.052,3)+breach_amount,
  left_repay_manager=round(manage_amount*0.0808/0.052,3),
  manage_amount=round(manage_amount*0.0808/0.052,3)
  WHERE order_no=t_order_no;
end $$
delimiter;

2. Update the order table (t_order_info)

drop procedure if exists update_t_order_info;
delimiter $$
create procedure update_t_order_info(IN orderNo varchar(64))
begin
  declare t_order_no varchar(64);
  set t_order_no=orderNo;
  SELECT left_amount into @m1 from t_order_repay WHERE order_no=t_order_no ORDER BY plan_time LIMIT 1;
  UPDATE t_order_info
  set manage_cost_rate=0.0808,
  manage_cost=round(manage_cost*0.0808/0.052,3),
  left_amount=borrow_amount+interest_amount+manage_cost,
  next_amount_need=@m1
  WHERE order_no=t_order_no;
end $$
delimiter;

3. Python calls the stored procedure in mysql

# encoding: utf-8
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
time1 = time.time()
import pandas as pd
import pymysql
############################################从数据库读数据###########################################
###########线上######################
# 加上字符集参数,防止中文乱码
# conn=pymysql.connect(
#  host="##########",
#  database="######",
#  user="####",
#  password="##########",
#  port=#######,
#  charset='utf8'
# )
# #############测试库######################
# ## 加上字符集参数,防止中文乱码
# conn=pymysql.connect(
#  host="172.16.34.32",
#  database="#########",
#  user="admin",
#  password="##############",
#  port=#########,
#  charset='utf8'
# )
#sql语句(安徽)
# sqlcmd="""
# SELECT order_no from t_order_info WHERE offline_org_no in(
# 0032,0035,0036
#
#
# ) and substr(create_time,1,10)>="2017-10-31"
#
# and `status` in(105,106,107,108)
#
# and manage_cost_rate=0.052
#
#
# """
#################sql语句(江苏)
# sqlcmd2="""
# SELECT order_no from t_order_info WHERE offline_org_no in(
# 0002,0005,0006,0007,0008,0009,0010,0011,0012,0013,0014,0017,0018,0019,0025,0026,0027,0028,0030,0031,0033,0034
# ) and substr(create_time,1,10)>="2017-10-31"
# and `status` in(105,106,107,108)
# and manage_cost_rate=0.052
#
# """
#利用pandas 模块导入mysql数据
# data=pd.read_sql(sqlcmd2,conn)
# print data
#
#
# ###################更新order_rapay表
# for each in data["order_no"]:
#   print each
#   # 创建游标
#   cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#   #有参数存储过程
#   cursor.execute('call update_t_order_rapay(%s)',(each))
#   conn.commit()
#
# print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
# #####################更新order_info表###################
# for each in data["order_no"]:
#   print each
#
#   # 创建游标
#   cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#   #有参数存储过程
#   cursor.execute('call update_t_order_info(%s)', (each))
#   conn.commit()
#
#
# cursor.close()
# print '调用存储过程完毕................'
# conn.close()
# time2=time.time()
# print u'总共耗时:' + str(time2 - time1) + 's'
Believe it or not After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

The object of diff is the virtual dom

Event emitter’s listening event

The above is the detailed content of Python calls mysql method to update data. 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 slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

What is the purpose of using arrays when lists exist in Python?What is the purpose of using arrays when lists exist in Python?May 01, 2025 am 12:04 AM

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

Explain how to iterate through the elements of a list and an array.Explain how to iterate through the elements of a list and an array.May 01, 2025 am 12:01 AM

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

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

Dreamweaver CS6

Dreamweaver CS6

Visual web 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),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.