7007 发表于 2018-8-7 13:27:28

python编写mysql类实现mysql的操作

#!/usr/local/env python3.6  
# -*- coding: UTF-8 -*-
  

  
import MySQLdb
  

  
class Mysql(object):
  
    def __init__(self,host,port,user,passwd,db,charset='utf8'):
  
      """初始化mysql连接"""
  
      try:
  
            self.conn = MySQLdb.connect(host,user,passwd,db,int(port))
  
      except MySQLdb.Error as e:
  
            errormsg = 'Cannot connect to server\nERROR(%s):%s' % (e.args,e.args)
  
            print(errormsg)
  
            exit(2)
  
      self.cursor = self.conn.cursor()
  

  
    def exec(self,sql):
  
      """执行dml,ddl语句"""
  
      try:
  
         self.cursor.execute(sql)
  
         self.conn.commit()
  
      except:
  
         self.conn.rollback()
  

  
    def query(self,sql):
  
      """查询数据"""
  
      self.cursor.execute(sql)
  
      return self.cursor.fetchall()
  

  
    def __del__(self):
  
      """ 关闭mysql连接 """
  
      self.conn.close()
  
      self.cursor.close()
页: [1]
查看完整版本: python编写mysql类实现mysql的操作