Python更新數(shù)據(jù)庫腳本兩種方法及對比介紹
最近項目的兩次版本迭代中,根據(jù)業(yè)務(wù)需求的變化,需要對數(shù)據(jù)庫進(jìn)行更新,兩次分別使用了不同的方式進(jìn)行更新。
第一種:使用python的MySQLdb模塊利用原生的sql語句進(jìn)行更新
import MySQLdb #主機(jī)名 HOST = '127.0.0.1' #用戶名 USER = "root" #密碼 PASSWD = "123456" #數(shù)據(jù)庫名 DB = "db_name" # 打開數(shù)據(jù)庫連接 db=MySQLdb.connect(HOST,USER,PASSWD,DB) # 獲取操作游標(biāo) cursor=db.cursor() if __name__ == '__main__': if cursor: command_a = "update tables_one set status=5 where status=0" # 使用execute方法執(zhí)行SQL語句 cursor.execute(command_a) # 提交到數(shù)據(jù)庫執(zhí)行 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() # 關(guān)閉數(shù)據(jù)庫連接 db.close()
數(shù)據(jù)庫查詢?nèi)N方式
- fetchone(): 該方法獲取下一個查詢結(jié)果集。結(jié)果集是一個對象
- fetchall():接收全部的返回結(jié)果行.
- rowcount: 這是一個只讀屬性,并返回執(zhí)行execute()方法后影響的行數(shù)。
第二種:使用python的框架flask和sqlalchemy進(jìn)行更新
# -*- 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) #鏈接數(shù)據(jù)庫路徑 app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://%s:%s@127.0.0.1:3306/%s?charset=%s' %(USER,PASSWD,DB,CHARTSET) #如果設(shè)置成 True (默認(rèn)情況),F(xiàn)lask-SQLAlchemy 將會追蹤對象的修改并且發(fā)送信號。這需要額外的內(nèi)存, 如果不必要的可以禁用它。 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True #如果設(shè)置成 True,SQLAlchemy 將會記錄所有 發(fā)到標(biāo)準(zhǔn)輸出(stderr)的語句,這對調(diào)試很有幫助。 app.config['SQLALCHEMY_ECHO'] = False # 數(shù)據(jù)庫連接池的大小。默認(rèn)是數(shù)據(jù)庫引擎的默認(rèn)值 (通常是 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 '<table_one com_name %r>' % self.com_name class Table_two(db.Model): __tablename__ = 'table_two' id = db.Column('id', db.Integer, primary_key=True, autoincrement=True) reason = db.Column('reason', db.String(128), nullable=True) create_time = db.Column('create_time', db.TIMESTAMP, server_default=text('now()')) status = db.Column('status', db.Integer, nullable=False, default=0) def __repr__(self): return '<table_two id %r>' % self.id def db_commit_all(lists): try: db.session.add_all(lists) db.session.commit() return 'SUCCESS' except Exception,e: return 'Fail!!!' def commits_to_three_judge(): com_sta_obj = Table_one.query.filter_by(com_name='只是測試使用,不用關(guān)心表間關(guān)系').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 '表同步結(jié)束' 64 if __name__=='__main__': #執(zhí)行更新數(shù)據(jù)庫函數(shù) commits_to_three_judge()
兩種方式對比:
1.在實(shí)際項目中,數(shù)據(jù)庫的更新 需要用到很多相關(guān)函數(shù)進(jìn)行數(shù)據(jù)的收集,判斷是否滿足條件等,而這些相關(guān)函數(shù)在項目中都是用 Sqlalchemy進(jìn)行數(shù)據(jù)相關(guān)操作,比如第二種方法里的db_commit_all()函數(shù)
2.使用第二種方法,直接復(fù)制這些函數(shù)到腳本中即可,如果使用第一種方法,則需要重寫相關(guān)函數(shù),增加開發(fā)時間,浪費(fèi)精力。
3.如果項目中是使用flask進(jìn)行開發(fā),推薦使用第二種方法進(jìn)行數(shù)據(jù)庫更新。
總結(jié)
以上所述是小編給大家介紹的Python更新數(shù)據(jù)庫腳本兩種方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- Python實(shí)戰(zhàn)之Elasticsearch的高級實(shí)現(xiàn)詳解
- python中的elasticsearch_dsl查詢語句轉(zhuǎn)換成es查詢語句詳解
- python中elasticsearch_dsl模塊的使用方法
- python 使用elasticsearch 實(shí)現(xiàn)翻頁的三種方式
- Python操作Elasticsearch處理timeout超時
- python3實(shí)現(xiàn)elasticsearch批量更新數(shù)據(jù)
- python更新數(shù)據(jù)庫中某個字段的數(shù)據(jù)(方法詳解)
- Python調(diào)用Elasticsearch更新數(shù)據(jù)庫的操作方法
相關(guān)文章
PyQT5實(shí)現(xiàn)選項卡窗口、堆棧窗口、停靠窗口、子窗口
這篇文章主要介紹了PyQT5實(shí)現(xiàn)選項卡窗口、堆棧窗口、??看翱凇⒆哟翱?,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04使用wxPython和pandas模塊生成Excel文件的代碼實(shí)現(xiàn)
在Python編程中,有時我們需要根據(jù)特定的數(shù)據(jù)生成Excel文件,本文將介紹如何使用wxPython和pandas模塊來實(shí)現(xiàn)這個目標(biāo),文中通過代碼示例給大家講解的非常詳細(xì),具有一定的參考價值,需要的朋友可以參考下2024-05-05python爬蟲基礎(chǔ)教程:requests庫(二)代碼實(shí)例
這篇文章主要介紹了python爬蟲基礎(chǔ)教程:requests庫(二),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04