在python脚本里执行

    sql_gp1 = "VACUUM dwd_access_record_inout_temp"
sql_gp2 = "delete from dwd_access_record_inout_temp t where t.indate > (select now()::timestamp-interval '36 hour')"
conn = gputil.connect(logger,target_host,target_user,target_password,target_db)
#gputil是自己导入pgdb写的模块
cur = conn.cursor()
cur.execute(sql_gp1)
cur.execute(sql_gp2)
conn.commit()
报错
    psycopg2.InternalError: VACUUM cannot run inside a transaction block
    
查阅资料
postgrel执行VACUUM报VACUUM cannot run inside a transaction block-LMLPHP
   
 报错的原因是:Psycopg2 会开启一个 新的 transaction 在每次调用 execute()时,而VACUUM需要在transaction之外执行,所以我们需要打开一个 autocommit connection 去执行 vacuum。
    
    
修改后代码:

 conn1 = gputil.connect(logger,target_host,target_user,target_password,target_db)
conn2 = psycopg2.connect(database=target_db, user=target_user, password=target_password,host=target_host)
# conn2.set_isolation_level(0) 如果psycopg是2.4.2版本前的,只能这样写
conn2.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cur1 = conn1.cursor()
cur2 = conn2.cursor() cur2.execute(sql_gp1) cur1.execute(sql_gp2)
conn1.commit() os.system("python /application/datax2/bin/datax.py /root/test_hgm/access_record_process/dwd_inout_temp.json")
conn1.commit()

  可能遇到的问题

    如果如下这样写,或者 或者自己用其他包写的conn2报下面的错了

conn2=gputil.connect(logger,target_host,target_user,target_password,target_db)

postgrel执行VACUUM报VACUUM cannot run inside a transaction block-LMLPHP
 
    用psycopg2包(pgdb包也是调用的psycopg2)调用connect()
conn2 = psycopg2.connect(database=target_db, user=target_user,password = target_password,host=target_host)

  

 
 
05-11 11:28