cl_303303303 发表于 2018-8-5 08:51:17

python3连接mysql-RickyHuL

class ConMysql:  def __init__(self, host, username, password, database):
  self._database = database
  self._host = host
  self._user = username
  self._passwd = password
  def connect(self):
  """连接数据库,执行SQL语句,返回元组"""
  #连接数据库
  try:
  self._db = pymysql.connect(self._host, self._user, self._passwd, self._database)
  except (ConnectionRefusedError, pymysql.err.OperationalError, pymysql.err.InternalError) as _con_err:
  return False, _con_err
  else:
  return True, 'OK'
  def get_data(self, _sql_str, s='r'):
  # 查询
  _cur = self._db.cursor()
  try:
  _cur.execute(_sql_str)
  except (pymysql.err.InternalError, pymysql.err.OperationalError, pymysql.err.ProgrammingError) as _sql_err:
  _cur.close()
  return False, _sql_err
  if s == 'r'
  _cur.close()
  _array = _cur.fetchall()
  return True, _array
  else:
  _cur.close()
  self._db.commit()
  return True, 'OK'
  def edit_data(self, _sql_str):
  # 修改
  return self.get_data(_sql_str, 'w')
  def __del__(self):
  self._db.close()
页: [1]
查看完整版本: python3连接mysql-RickyHuL