我使用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(),当您没有打开事务时就不能提交.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。