写一个连接数据库且可以修改的监听器
时间: 2024-03-16 21:43:50 浏览: 14
以下是一个Python连接数据库且可以修改的监听器的代码示例:
``` python
import psycopg2
def connect_to_database():
try:
conn = psycopg2.connect(
host="your_host",
database="your_database",
user="your_username",
password="your_password"
)
print("Successfully connected to database!")
return conn
except psycopg2.OperationalError:
print("Connection failed!")
return None
def listen_to_database(conn):
if conn is None:
print("No database connection!")
return
cur = conn.cursor()
cur.execute("LISTEN your_channel;")
conn.commit()
print("Listening to database changes...")
while True:
conn.poll()
while conn.notifies:
notify = conn.notifies.pop(0)
print("Received notification: ", notify)
def main():
conn = connect_to_database()
listen_to_database(conn)
if __name__ == '__main__':
main()
```
这段代码使用了`psycopg2`库来连接PostgreSQL数据库,并且使用了一个监听器来监听数据库中指定的频道。你可以通过修改`connect_to_database()`函数中的连接参数来连接不同的数据库,并且可以在`listen_to_database()`函数中修改`your_channel`来监听不同的频道。在监听器启动后,它将会不断监听数据库的变化并打印出通知的内容。