python串連mysql資料庫封裝

來源:互聯網
上載者:User

標籤:rom   資料庫   .com   value   com   from   base   bsp   cep   

源碼:

 1 import pymysql 2  3 class MysqlConnect(object): 4     # 魔術方法, 初始化, 建構函式 5     def __init__(self): 6         self.db = pymysql.connect(host=‘127.0.0.1‘, user=‘root‘, password=‘123456‘,port=3306, database=‘xueqiu‘) 7         self.cursor = self.db.cursor() 8  9     def exec(self,sql):10         try:11             # 執行SQL語句12             self.cursor.execute(sql)13             # 提交到資料庫執行14             self.db.commit()15         except:16             # 發生錯誤時復原17             self.db.rollback()18 19     def select(self,sql):20         try:21             self.cursor.execute(sql)22             # 擷取所有記錄列表23             results = self.cursor.fetchall()24             for row in results:25                 print(row)26         except:27             print("Error: unable to fetch data")28 29     # 魔術方法, 析構化 ,解構函式30     def __del__(self):31         self.cursor.close()32         self.db.close()33 34 if __name__ == ‘__main__‘:35     mc = MysqlConnect()36     # mc.exec(‘insert into news(id) values(1111111)‘)37     print(mc.select(‘select * from news;‘))

 

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.