db.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. import pymysql
  4. import psycopg2
  5. class DB():
  6. def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PWD, DB_NAME, DB='mysql'):
  7. self.DB_HOST = DB_HOST # 设置MYSQL地址
  8. self.DB_PORT = DB_PORT # 设置端口号
  9. self.DB_USER = DB_USER # 设置用户名
  10. self.DB_PWD = DB_PWD # 设置密码
  11. self.DB_NAME = DB_NAME # 数据库名
  12. self.DB = DB # 连接哪种数据库,mysql或者pgsql
  13. self.conn = self.getConnection()
  14. def getConnection(self):
  15. # 连接哪种数据库
  16. if self.DB == 'pgsql':
  17. return psycopg2.connect(
  18. host=self.DB_HOST,
  19. port=self.DB_PORT,
  20. user=self.DB_USER,
  21. password=self.DB_PWD,
  22. database=self.DB_NAME,
  23. )
  24. elif self.DB == 'mysql':
  25. return pymysql.Connect(
  26. host=self.DB_HOST,
  27. port=self.DB_PORT,
  28. user=self.DB_USER,
  29. password=self.DB_PWD,
  30. database=self.DB_NAME,
  31. charset='utf8'
  32. )
  33. else:
  34. raise ("请选择正确连接数据库方式,mysql或者pgsql")
  35. def close(self):
  36. self._close(self.conn.cursor())
  37. # 查询方法
  38. def query(self, sqlString):
  39. cursor = self.conn.cursor()
  40. cursor.execute(sqlString)
  41. returnData = cursor.fetchall()
  42. # self._close(cursor)
  43. return returnData
  44. # 获取单条数据
  45. def find_one(self, sqlString):
  46. cursor = self.conn.cursor()
  47. cursor.execute(sqlString)
  48. returnData = cursor.fetchone()
  49. self._close(cursor)
  50. return returnData
  51. # 不带参数的更新方法
  52. def update(self, sqlString):
  53. cursor = self.conn.cursor()
  54. cursor.execute(sqlString)
  55. self.conn.commit()
  56. # 带参数的更新方法
  57. def updateByParam(self, sqlString, params):
  58. cursor = self.conn.cursor()
  59. cursor.execute(sqlString, params)
  60. self.conn.commit()
  61. self._close(cursor)
  62. # 关闭回收资源
  63. def _close(self, cursor):
  64. cursor.close()
  65. self.conn.close()
  66. # if __name__ == "__main__":
  67. # db = DB('localhost', 3306, 'root', '123456', 'zuqiu')
  68. # sql = "show create table dc_sclassinfo;"
  69. # result = db.query(sql)
  70. # pycomm.toLog(result)