python之MySQL學習——簡單的增刪改查封裝

來源:互聯網
上載者:User

標籤:錯誤   database   ams   nbsp   close   insert   .exe   llb   ase   

1.增刪改查封裝類MysqlHelper.py

 1 import pymysql as ps 2  3 class MysqlHelper: 4     def __init__(self, host, user, password, database, charset): 5         self.host = host 6         self.user = user 7         self.password = password 8         self.database = database 9         self.charset = charset10         self.db = None11         self.curs = None12     # 資料庫連接13     def open(self):14         self.db = ps.connect(host=self.host, user=self.user, password=self.password,database=self.database, charset=self.charset)15         self.curs = self.db.cursor()16     # 資料庫關閉17     def close(self):18         self.curs.close()19         self.db.close()20     # 資料增刪改21     def cud(self, sql, params):22         self.open()23         try:24             self.curs.execute(sql, params)25             self.db.commit()26             print("ok")27         except :28             print(‘cud出現錯誤‘)29             self.db.rollback()30         self.close()31     # 資料查詢32     def find(self, sql, params):33         self.open()34         try:35             result = self.curs.execute(sql, params)36             self.close()37             print("ok")38             return result39         except:40             print(‘find出現錯誤‘)

2.資料查詢(引入封裝類)

1 from MysqlHelper import MysqlHelper2 3 mh = MysqlHelper(‘localhost‘, ‘root‘, ‘123456‘, ‘test‘, ‘utf8‘)4 sql = "select * from user where name=%s"5 print(mh.find(sql, ‘小明‘))

3.資料修改(引入封裝類)

1 from MysqlHelper import MysqlHelper2 3 mh = MysqlHelper(‘localhost‘, ‘root‘, ‘123456‘, ‘test‘, ‘utf8‘)4 sql = "insert into user(name,password) values(%s,%s)"5 mh.cud(sql, (‘小光‘, ‘123456‘))

 

python之MySQL學習——簡單的增刪改查封裝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.