db.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. def getConn(self):
  45. return self.conn
  46. def getCursor(self):
  47. return self.conn.cursor()
  48. # 获取单条数据
  49. def find_one(self, sqlString):
  50. cursor = self.conn.cursor()
  51. cursor.execute(sqlString)
  52. returnData = cursor.fetchone()
  53. self._close(cursor)
  54. return returnData
  55. # 不带参数的更新方法
  56. def update(self, sqlString):
  57. cursor = self.conn.cursor()
  58. cursor.execute(sqlString)
  59. self.conn.commit()
  60. # 带参数的更新方法
  61. def updateByParam(self, sqlString, params):
  62. cursor = self.conn.cursor()
  63. cursor.execute(sqlString, params)
  64. self.conn.commit()
  65. self._close(cursor)
  66. # 关闭回收资源
  67. def _close(self, cursor):
  68. cursor.close()
  69. self.conn.close()
  70. # if __name__ == "__main__":
  71. # db = DB('localhost', 3306, 'root', '123456', 'zuqiu')
  72. # sql = "show create table dc_sclassinfo;"
  73. # result = db.query(sql)
  74. # pycomm.toLog(result)