国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python數據操作方法封裝類實例

2019-11-25 16:04:19
字體:
來源:轉載
供稿:網友

本文實例講述了Python數據操作方法封裝類。分享給大家供大家參考,具體如下:

工作中經常會用到數據的插敘、單條數據插入和批量數據插入,以下是本人封裝的一個類,推薦給各位:

#!/usr/bin/env python# -*- coding:utf-8 -*-# Author:Eric.yueimport loggingimport MySQLdbclass _MySQL(object):  def __init__(self,host, port, user, passwd, db):    self.conn = MySQLdb.connect(      host = host,      port = port,      user = user,      passwd = passwd,      db = db,      charset='utf8'    )  def get_cursor(self):    return self.conn.cursor()  def query(self, sql):    cursor = self.get_cursor()    try:      cursor.execute(sql, None)      result = cursor.fetchall()    except Exception, e:      logging.error("mysql query error: %s", e)      return None    finally:      cursor.close()    return result  def execute(self, sql, param=None):    cursor = self.get_cursor()    try:      cursor.execute(sql, param)      self.conn.commit()      affected_row = cursor.rowcount    except Exception, e:      logging.error("mysql execute error: %s", e)      return 0    finally:      cursor.close()    return affected_row  def executemany(self, sql, params=None):    cursor = self.get_cursor()    try:      cursor.executemany(sql, params)      self.conn.commit()      affected_rows = cursor.rowcount    except Exception, e:      logging.error("mysql executemany error: %s", e)      return 0    finally:      cursor.close()    return affected_rows  def close(self):    try:      self.conn.close()    except:      pass  def __del__(self):    self.close()mysql = _MySQL('127.0.0.1', 3306, 'root', '123456', 'test')def create_table():  table = """      CREATE TABLE IF NOT EXISTS `watchdog`(        `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,        `name` varchar(100),        `price` int(11) NOT NULL DEFAULT 0      ) ENGINE=InnoDB charset=utf8;      """  print mysql.execute(table)def insert_data():  params = [('dog_%d' % i, i) for i in xrange(12)]  sql = "INSERT INTO `watchdog`(`name`,`price`) VALUES(%s,%s);"  print mysql.executemany(sql, params)if __name__ == '__main__':  create_table()  insert_data()

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python常見數據庫操作技巧匯總》、《Python編碼操作技巧總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 孟州市| 绿春县| 呈贡县| 灵宝市| 大理市| 闵行区| 鄂尔多斯市| 五莲县| 乌拉特中旗| 静宁县| 延吉市| 集贤县| 樟树市| 东辽县| 图们市| 色达县| 雅安市| 崇义县| 厦门市| 文化| 九龙坡区| 福海县| 昭觉县| 阿图什市| 梧州市| 五寨县| 井冈山市| 江西省| 赫章县| 德钦县| 隆德县| 伊金霍洛旗| 玉林市| 马山县| 临颍县| 澄江县| 额尔古纳市| 浦城县| 富宁县| 田东县| 甘肃省|