python - Postgres 引发 "ACTIVE SQL TRANSACTION"(错误代码 : 25001)

标签 python postgresql psycopg2

我使用 psycopg2 在 python 中访问我的 postgres 数据库。我的函数应该创建一个新数据库,代码如下所示:

def createDB(host, username, dbname):
  adminuser = settings.DB_ADMIN_USER
  adminpass = settings.DB_ADMIN_PASS

  try:
    conn=psycopg2.connect(user=adminuser, password=adminpass, host=host)
    cur = conn.cursor()
    cur.execute("CREATE DATABASE %s OWNER %s" % (nospecial(dbname), nospecial(username)))
    conn.commit()
  except Exception, e:
    raise e
  finally:
    cur.close()
    conn.close()

def nospecial(s):
  pattern = re.compile('[^a-zA-Z0-9_]+')
  return pattern.sub('', s)

当我调用 createDB 时,我的 postgres 服务器抛出一个错误: CREATE DATABASE 不能在事务 block 内运行 错误代码 25001 代表“ACTIVE SQL TRANSACTION”。

我很确定没有其他连接同时运行,并且我在调用 createDB 之前使用的每个连接都已关闭。

最佳答案

看起来你的 cursor() 实际上是一个事务: http://initd.org/psycopg/docs/cursor.html#cursor

Cursors created from the same connection are not isolated, i.e., any changes done to the database by a cursor are immediately visible by the other cursors. Cursors created from different connections can or can not be isolated, depending on the connections’ isolation level. See also rollback() and commit() methods.

跳过光标,直接执行您的查询。也删除 commit(),当你没有打开事务时你不能提交。

关于python - Postgres 引发 "ACTIVE SQL TRANSACTION"(错误代码 : 25001),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3413646/

相关文章:

python - 如何使用pytest测试异步功能?

python - 什么时候应该使用 Tensorflow 变量,什么时候应该使用 numpy 或 python 变量

Python 请求 SSL 主机名不匹配错误

sql - 从另一个表插入 SELECT MAX

postgresql - 调用 PL/pgSQL 函数忽略结果

python postgres 在读取结果时更改行的值

python - 独特的值(value) python

Postgresql - NULL 的解释类型错误

python - psycopg2如何处理TypeError : not all arguments converted during string formatting

python - 尝试使用 psycopg2 连接到远程数据库时,将 ssl 证书放在哪里?