PostgreSQL.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. __author__ = 'wanger'
  3. __date__ = '2024-08-20'
  4. __copyright__ = '(C) 2024 by siwei'
  5. __revision__ = '1.0'
  6. import time
  7. from typing import Optional
  8. import os
  9. import psycopg2
  10. import uuid
  11. import siwei_config
  12. class PostgreSQL:
  13. # 用户表
  14. Sys_user = "sys_user"
  15. # 全局参数修改
  16. db_config = siwei_config.CONFIG['db']
  17. def __init__(
  18. self,
  19. host: Optional[str] = db_config['host'], # default host during installation
  20. port: Optional[str] = db_config['port'], # default port during pg installation
  21. user: Optional[str] = db_config['user'], # default user during pg installation
  22. password: Optional[str] = db_config['password'], # default password during pg installation
  23. dbname: Optional[str] = db_config['name'], # default dbname during pg installation
  24. schema: Optional[str] = db_config['schema']
  25. ):
  26. # 配置数据库连接参数并指定schema
  27. self.connparams = {
  28. "dbname": dbname,
  29. "user": user,
  30. "password": password,
  31. "host": host,
  32. "port": port,
  33. "options": "-c search_path=otherSchema," + schema if schema is not None else None
  34. }
  35. self.conn = psycopg2.connect(**self.connparams)
  36. # 创建一个游标对象
  37. self.cur = self.conn.cursor()
  38. def execute(self, sql):
  39. # 执行一个查询
  40. self.cur.execute(sql)
  41. # 获取查询结果
  42. return self.cur.fetchall()
  43. def close(self):
  44. # 关闭游标和连接
  45. self.cur.close()
  46. self.conn.close()
  47. # 根据用户名查询密码
  48. def getPasswordByUsername(self, username):
  49. sql = "SELECT password FROM {} t where t.user_name = '{}'".format(self.Sys_user, username)
  50. self.cur.execute(sql)
  51. rows = self.cur.fetchall()
  52. return rows
  53. # 判断数据是否为字符串
  54. def is_string(self, var):
  55. return isinstance(var, str)