import pymysql # 鏈接mysql的三方庫,能夠pip3 install pymysql安裝 def exc1(host, port, db, charset, sql): conn = pymysql.connect(host, port, db, charset) conn.execute(sql) return xxx def exc2(proc_name): conn = pymysql.connect(host, port, db, charsett) conn.call_proc(sql) return xxx exc1('1.1.1.1', 3306, 'db1', 'utf-8', 'select * from t1') exc1('1.1.1.1', 3306, 'db1', 'utf-8', 'select * from t2') exc1('1.1.1.1', 3306, 'db1', 'utf-8', 'select * from t3') exc1('1.1.1.1', 3306, 'db1', 'utf-8', 'select * from t4')
* 因爲host、port、db、charset多是固定不變的,sql一直在變化,所以咱們經過上述的方法實現不一樣的sql語句,很是麻煩,所以咱們能夠改用默認形參python
def exc1(sql, host='1.1.1.1', port=3306, db='db1', charset='utf-8'): conn = pymysql.connect(host, port, db, charset) conn.execute(sql) return xxx exc1('select * from t1') exc1('select * from t2') exc1('select * from t3') exc1('select * from t4')
* 雖然是用默認參數簡化了操做,可是對於不一樣引用的對象,參數並非一成不變的,或者咱們須要對exc2方法進行修改,這是很是麻煩的,所以能夠考慮使用面向對象mysql
* 有了面向對象以後,對於上述的例子,咱們能夠這樣作sql
import pymysql class Foo: def __init__(self, host, port, db, chartset): self.host = host self.port = port self.db = db self.charset = chartset def exc1(self, sql): conn = pymysql.connect(self.host, self.port, self.db, self.charset) conn.execute(sql) return xxx def exc2(self, proc_name): conn = pymysql.connect(self.host, self.port, self.db, self.charsett) conn.call_proc(sql) return xxx obj1 = Foo('1.1.1.1', 3306, 'db1', 'utf-8') obj1.exc1('select * from t1') obj1.exc1('select * from t2') obj1.exc1('select * from t3') obj1.exc1('select * from t4') obj2 = Foo('1.1.1.2', 3306, 'db1', 'utf-8') obj2.exc1('select * from t4')
* 對於上述發生的現象,咱們能夠總結對象其實就是一個高度整合的產物,整合數據與專門操做該數據的方法(綁定方法)數據庫