psycopg2无法执行多个查询

2024-06-26 13:25:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用psycopg2对psqldb执行多个查询时遇到问题。示例:

#!/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函数中打开第二个连接时,第一个提交没有在数据库上执行,这是没有意义的。在

我做错什么了?在


Tags: importclosedefconnectpostgresrootpasswordconn
1条回答
网友
1楼 · 发布于 2024-06-26 13:25:36

看起来您刚刚颠倒了第二个查询中的两个参数:

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

医生的一些帮助:

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

相关问题 更多 >