写一个健壮的 python3.8 连接 postgres 数据库 jdbc工具类
时间: 2024-02-18 18:00:23 浏览: 187
好的,以下是一个简单的 Python 3.8 连接 PostgreSQL 数据库的健壮的 JDBC 工具类:
```python
import psycopg2
class PostgreSQLJDBC:
def __init__(self, host, port, username, password, database):
self.host = host
self.port = port
self.username = username
self.password = password
self.database = database
self.connection = None
def open_connection(self):
try:
self.connection = psycopg2.connect(
host=self.host,
port=self.port,
user=self.username,
password=self.password,
database=self.database
)
except (Exception, psycopg2.DatabaseError) as error:
print(f"Error while connecting to PostgreSQL: {error}")
def execute_query(self, query):
try:
cursor = self.connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
return result
except (Exception, psycopg2.DatabaseError) as error:
print(f"Error while executing query: {error}")
def close_connection(self):
if self.connection:
self.connection.close()
print("PostgreSQL connection is closed")
```
在使用时,可以按照以下步骤:
```python
jdbc = PostgreSQLJDBC("hostname", 5432, "username", "password", "database")
jdbc.open_connection()
result = jdbc.execute_query("SELECT * FROM table_name")
print(result)
jdbc.close_connection()
```
其中,分别传入 PostgreSQL 的主机名、端口号、用户名、密码和数据库名,调用 `open_connection` 方法建立连接,调用 `execute_query` 方法执行 SQL 查询,调用 `close_connection` 方法关闭连接。
阅读全文