search
HomeBackend DevelopmentPython TutorialExamples of updating database scripts that can be implemented using two methods in python

In the two recent version iterations of the project, the database needed to be updated according to changes in business requirements, and different methods were used for the updates twice.

The first one: Use python’s MySQLdb module to update using native sql statements

import MySQLdb
#主机名
HOST = '127.0.0.1'
#用户名
USER = "root"
#密码
PASSWD = "123456"
#数据库名
DB = "db_name"
# 打开数据库连接
db=MySQLdb.connect(HOST,USER,PASSWD,DB)
# 获取操作游标
cursor=db.cursor()

if __name__ == '__main__':

    if cursor:
        command_a = "update tables_one set status=5 where status=0"
        # 使用execute方法执行SQL语句
        cursor.execute(command_a)
        # 提交到数据库执行
        db.commit()

        command2 = "select field from tables_one where id =12"
        ret2 = cursor.execute(command2)
        # 获取所有记录列表
        ret2=cursor.fetchall()
        for item in ret2:
                command3 = "insert into tables_two(name) values (%s);" % (item[0])
                fin=cursor.execute(command3)
                db.commit()
        # 关闭数据库连接
        db.close()

Three ways to query the database

  • fetchone(): This method gets the next query result set. The result set is an object

  • fetchall():Receives all returned result rows.

  • rowcount : This is a read-only property and returns the number of rows affected after executing the execute() method.

Second: Use python’s framework flask and sqlalchemy to update

# -*- coding:utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text

HOST = '127.0.0.1'
USER = "root"
PASSWD = "123456"
DB = "carrier_test"
CHARTSET = "utf8"

app = Flask(__name__,instance_relative_config = True)
#链接数据库路径
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://%s:%s@127.0.0.1:3306/%s?charset=%s' %(USER,PASSWD,DB,CHARTSET)
#如果设置成 True (默认情况),Flask-SQLAlchemy 将会追踪对象的修改并且发送信号。这需要额外的内存, 如果不必要的可以禁用它。
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
#如果设置成 True,SQLAlchemy 将会记录所有 发到标准输出(stderr)的语句,这对调试很有帮助。
app.config['SQLALCHEMY_ECHO'] = False
# 数据库连接池的大小。默认是数据库引擎的默认值 (通常是 5)。
app.config['SQLALCHEMY_POOL_SIZE'] = 6
db = SQLAlchemy(app)

class Table_one(db.Model):
    __tablename__ = 'table_one'

    id = db.Column('id', db.Integer, primary_key=True, autoincrement=True)
    com_name = db.Column('com_name', db.String(30), nullable=False)
    com_about = db.Column('com_about', db.String(200), nullable=False)

    def __repr__(self):
        return &#39;<table_one com_name %r>&#39; % self.com_name


class Table_two(db.Model):
    __tablename__ = &#39;table_two&#39;

    id = db.Column(&#39;id&#39;, db.Integer, primary_key=True, autoincrement=True)
    reason = db.Column(&#39;reason&#39;, db.String(128), nullable=True)
    create_time = db.Column(&#39;create_time&#39;, db.TIMESTAMP, server_default=text(&#39;now()&#39;))
    status = db.Column(&#39;status&#39;, db.Integer, nullable=False, default=0)

    def __repr__(self):
        return &#39;<table_two id %r>&#39; % self.id

def db_commit_all(lists):
    try:
        db.session.add_all(lists)
        db.session.commit()
        return &#39;SUCCESS&#39;
    except Exception,e:
        return &#39;Fail!!!&#39;

def commits_to_three_judge():
    com_sta_obj = Table_one.query.filter_by(com_name=&#39;只是测试使用,不用关心表间关系&#39;).all()
    for ite in com_sta_obj:
        ship_obj = Table_two.query.filter_by(id=ite.id).first()
        if ship_obj:
            if int(ship_obj.status) == 2:
                ite.status = 0
                print db_commit_all([ite])
    print &#39;表同步结束&#39;

64 
if __name__==&#39;__main__&#39;:
    #执行更新数据库函数
    commits_to_three_judge()

Comparison of two methods:

1. In actual projects, database updates require the use of many related functions to collect data, determine whether conditions are met, etc. These related functions use Sqlalchemy for data-related operations in the project, such as the db_commit_all() function in the second method

2. Using the second method, just copy these functions directly into the script. , If you use the first method, you need to rewrite related functions, which increases development time and wastes energy.

3. If the project is developed using flask, it is recommended to use the second method to update the database.

The above is the detailed content of Examples of updating database scripts that can be implemented using two methods in python. 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
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.