標籤: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資料庫封裝