小编xmr*_*mrG的帖子

Python psycopg2-记录事件

我正在使用psycopg2,并且在将事件(执行的查询,通知,错误)记录到文件时遇到问题。我想在PgAdmin历史记录窗口中获得效果。

例如,我正在执行以下查询:

insert into city(id, name, countrycode, district, population) values (4080,'Savilla', 'ESP', 'andalucia', 1000000)
Run Code Online (Sandbox Code Playgroud)

在PgAdmin中,我看到这样的效果:

Executing query: 
insert into city(id, name, countrycode, district, population) values (4080,'Sevilla', 'ESP', 'andalucia', 1000000)

Query executed in 26 ms.
One row affected.
Run Code Online (Sandbox Code Playgroud)

使用psycopg2可以获得类似的效果吗?

我尝试使用LoggingCursor,但对我来说并不令人满意,因为它仅记录查询。

感谢帮助。


编辑:

我的代码:

conn = psycopg2.extras.LoggingConnection(DSN)
File=open('log.log','a')
File.write('================================')
psycopg2.extras.LoggingConnection.initialize(conn,File)

File.write('\n'+time.strftime("%Y-%m-%d %H:%M:%S") + '---Executing query:\n\t')
q="""insert into city(id, name, countrycode, district, population) values (4080,'Sevilla', 'ESP', 'andalucia', 10000)"""
c=conn.cursor()
c.execute(q)
File.write('\n'+time.strftime("%Y-%m-%d %H:%M:%S") + '---Executing query:\n\t')
q="""delete from city where id = …
Run Code Online (Sandbox Code Playgroud)

python postgresql psycopg2 pgadmin

5
推荐指数
1
解决办法
3776
查看次数

标签 统计

pgadmin ×1

postgresql ×1

psycopg2 ×1

python ×1