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

我使用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无法在事务块内运行
错误代码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(),当您没有打开事务时就不能提交.

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...