最近項目的兩次版本迭代中,根據業務需求的變化,需要對數據庫進行更新,兩次分別使用了不同的方式進行更新。
第一種:使用python的MySQLdb模塊利用原生的sql語句進行更新
1 import MySQLdb 2 #主機名 3 HOST = '127.0.0.1' 4 #用戶名 5 USER = "root" 6 #密碼 7 PASSWD = "123456" 8 #數據庫名 9 DB = "db_name" 10 # 打開數據庫連接 11 db=MySQLdb.connect(HOST,USER,PASSWD,DB) 12 # 獲取操作游標 13 cursor=db.cursor() 14 15 if __name__ == '__main__': 16 17 if cursor: 18 command_a = "update tables_one set status=5 where status=0" 19 # 使用execute方法執行SQL語句 20 cursor.execute(command_a) 21 # 提交到數據庫執行 22 db.commit() 23 24 command2 = "select field from tables_one where id =12" 25 ret2 = cursor.execute(command2) 26 # 獲取所有記錄列表 27 ret2=cursor.fetchall() 28 for item in ret2: 29 command3 = "insert into tables_two(name) values (%s);" % (item[0]) 30 fin=cursor.execute(command3) 31 db.commit() 32 # 關閉數據庫連接 33 db.close()
數據庫查詢三種方式
- fetchone(): 該方法獲取下一個查詢結果集。結果集是一個對象
- fetchall():接收全部的返回結果行.
- rowcount: 這是一個只讀屬性,並返回執行execute()方法后影響的行數。
第二種:使用python的框架flask和sqlalchemy進行更新
1 # -*- coding:utf-8 -*-
2 from flask import Flask
3 from flask_sqlalchemy import SQLAlchemy
4 from sqlalchemy.sql import text
5
6 HOST = '127.0.0.1'
7 USER = "root"
8 PASSWD = "123456"
9 DB = "carrier_test"
10 CHARTSET = "utf8"
11
12 app = Flask(__name__,instance_relative_config = True)
13 #鏈接數據庫路徑
14 app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://%s:%s@127.0.0.1:3306/%s?charset=%s' %(USER,PASSWD,DB,CHARTSET)
15 #如果設置成 True (默認情況),Flask-SQLAlchemy 將會追蹤對象的修改並且發送信號。這需要額外的內存, 如果不必要的可以禁用它。
16 app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
17 #如果設置成 True,SQLAlchemy 將會記錄所有 發到標准輸出(stderr)的語句,這對調試很有幫助。
18 app.config['SQLALCHEMY_ECHO'] = False
19 # 數據庫連接池的大小。默認是數據庫引擎的默認值 (通常是 5)。
20 app.config['SQLALCHEMY_POOL_SIZE'] = 6
21 db = SQLAlchemy(app)
22
23 class Table_one(db.Model):
24 __tablename__ = 'table_one'
25
26 id = db.Column('id', db.Integer, primary_key=True, autoincrement=True)
27 com_name = db.Column('com_name', db.String(30), nullable=False)
28 com_about = db.Column('com_about', db.String(200), nullable=False)
29
30 def __repr__(self):
31 return '<table_one com_name %r>' % self.com_name
32
33
34 class Table_two(db.Model):
35 __tablename__ = 'table_two'
36
37 id = db.Column('id', db.Integer, primary_key=True, autoincrement=True)
38 reason = db.Column('reason', db.String(128), nullable=True)
39 create_time = db.Column('create_time', db.TIMESTAMP, server_default=text('now()'))
40 status = db.Column('status', db.Integer, nullable=False, default=0)
41
42 def __repr__(self):
43 return '<table_two id %r>' % self.id
44
45 def db_commit_all(lists):
46 try:
47 db.session.add_all(lists)
48 db.session.commit()
49 return 'SUCCESS'
50 except Exception,e:
51 return 'Fail!!!'
52
53 def commits_to_three_judge():
54 com_sta_obj = Table_one.query.filter_by(com_name='只是測試使用,不用關心表間關系').all()
55 for ite in com_sta_obj:
56 ship_obj = Table_two.query.filter_by(id=ite.id).first()
57 if ship_obj:
58 if int(ship_obj.status) == 2:
59 ite.status = 0
60 print db_commit_all([ite])
61 print '表同步結束'
62
63 64
65 if __name__=='__main__':
66 #執行更新數據庫函數
67 commits_to_three_judge()
兩種方式對比:
1.在實際項目中,數據庫的更新 需要用到很多相關函數進行數據的收集,判斷是否滿足條件等,而這些相關函數在項目中都是用 Sqlalchemy進行數據相關操作,比如第二種方法里的db_commit_all()函數
2.使用第二種方法,直接復制這些函數到腳本中即可,如果使用第一種方法,則需要重寫相關函數,增加開發時間,浪費精力。
3.如果項目中是使用flask進行開發,推薦使用第二種方法進行數據庫更新。
