PostgreSQL.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. class PostgreSQL:
  12. # 用户表
  13. Sys_user = "sys_user"
  14. def __init__(
  15. self,
  16. host: Optional[str] = "192.168.60.52", # default host during installation
  17. port: Optional[str] = "5432", # default port during pg installation
  18. user: Optional[str] = "postgres", # default user during pg installation
  19. password: Optional[str] = "postgres", # default password during pg installation
  20. dbname: Optional[str] = "real3d", # default dbname during pg installation
  21. schema: Optional[str] = None
  22. ):
  23. # 配置数据库连接参数并指定schema
  24. self.connparams = {
  25. "dbname": dbname,
  26. "user": user,
  27. "password": password,
  28. "host": host,
  29. "port": port,
  30. "options": "-c search_path=otherSchema," + schema if schema is not None else None
  31. }
  32. self.conn = psycopg2.connect(**self.connparams)
  33. # 创建一个游标对象
  34. self.cur = self.conn.cursor()
  35. def execute(self, sql):
  36. # 执行一个查询
  37. self.cur.execute(sql)
  38. # 获取查询结果
  39. return self.cur.fetchall()
  40. def close(self):
  41. # 关闭游标和连接
  42. self.cur.close()
  43. self.conn.close()
  44. # 根据用户名查询密码
  45. def getPasswordByUsername(self, username):
  46. sql = "SELECT password FROM {} t where t.user_name = '{}'".format(self.Sys_user, username)
  47. self.cur.execute(sql)
  48. rows = self.cur.fetchall()
  49. return rows
  50. # 判断数据是否为字符串
  51. def is_string(self, var):
  52. return isinstance(var, str)