python 封装一个标准的postgres jdbc 工具类, 执行sql的结果以列表字典形式返回
时间: 2024-03-12 09:49:03 浏览: 174
orm.py:Python 和 Postgres 的最小形式
好的,下面是一个封装了标准的postgres jdbc工具类的Python代码,执行SQL的结果以列表字典形式返回:
```python
import psycopg2
class PostgresJDBC:
def __init__(self, host, port, dbname, user, password):
self.host = host
self.port = port
self.dbname = dbname
self.user = user
self.password = password
self.conn = None
def connect(self):
try:
self.conn = psycopg2.connect(
host=self.host,
port=self.port,
dbname=self.dbname,
user=self.user,
password=self.password
)
except psycopg2.Error as e:
print(f"Error connecting to Postgres database: {e}")
def disconnect(self):
if self.conn:
self.conn.close()
def execute_query(self, query):
try:
cursor = self.conn.cursor()
cursor.execute(query)
rows = cursor.fetchall()
columns = [desc[0] for desc in cursor.description]
result = []
for row in rows:
result.append(dict(zip(columns, row)))
return result
except psycopg2.Error as e:
print(f"Error executing query: {e}")
```
使用方法:
```python
# 初始化PostgresJDBC对象
jdbc = PostgresJDBC(
host="localhost",
port="5432",
dbname="mydatabase",
user="myusername",
password="mypassword"
)
# 连接到PostgreSQL数据库
jdbc.connect()
# 执行查询语句
result = jdbc.execute_query("SELECT * FROM mytable")
# 打印结果
print(result)
# 断开与数据库的连接
jdbc.disconnect()
```
注意:在使用该工具类之前,需要确保已安装 `psycopg2` 模块,可以通过以下命令来安装:
```
pip install psycopg2
```
阅读全文