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(),当您没有打开事务时就不能提交.

上一篇:在anaconda安装psycopg2


下一篇:python-psycopg2.InterfaceError:连接已关闭/ pgr_astar