python – psycopg2无法执行多个查询

我在使用psycopg2在我的psql数据库上执行多个查询时遇到问题.例:

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import psycopg2
from psycopg2.extras import RealDictCursor

def CreateUser(user, mySchema):

    conn = psycopg2.connect("dbname='postgres' user='root' password='somePassword' host='localhost'")
    cur = conn.cursor()
    cur.execute("""create user %s""" % (user)) 
    conn.commit()
    cur.close()
    conn.close()
    CreateSchema(user, mySchema)


def CreateSchema(user, mySchema):
    conn = psycopg2.connect("dbname='postgres' user='root' password='somePassword' host='localhost'")
    cur = conn.cursor()
    cur.execute("""create schema %s authorization %s """ % (user,mySchema))
    conn.commit()
    cur.close()
    conn.close()

def FetchUserInput():
    userInput = raw_input("UserName")
    mySchema = raw_input("SchemaName")
    CreateUser(userInput, mySchema)


FetchUserInput()

在这种情况下,第二个查询失败,并且先前用户创建的错误不存在!
如果我只执行CreateUser函数,它可以正常工作.
如果我在psql中手动执行它,它可以正常工作.

如果我在CreateSchema函数中打开第二个连接时没有在数据库上执行第一次提交,这没有任何意义.

我究竟做错了什么?

最佳答案 看起来你刚刚在第二个查询中反转了2个参数:

cur.execute("""CREATE SCHEMA %s AUTHORIZATION %s """ % (mySchema, user))

来自doc的一些帮助:

CREATE SCHEMA schema_name [ AUTHORIZATION user_name ] [ schema_element [ … ] ]

CREATE SCHEMA AUTHORIZATION user_name [ schema_element [ … ] ]

CREATE SCHEMA IF NOT EXISTS schema_name [ AUTHORIZATION user_name ]

CREATE SCHEMA IF NOT EXISTS AUTHORIZATION user_name

点赞