【问题标题】:psycopg2 cannot execute multiple queriespsycopg2 无法执行多个查询
【发布时间】:2017-09-10 20:48:13
【问题描述】:

我在使用 psycopg2 在我的 psql db 上执行多个查询时遇到问题。示例:

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

我做错了什么?

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    看起来您刚刚在第二个查询中反转了 2 个参数:

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

    来自文档的一些帮助:

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

    CREATE SCHEMA AUTHORIZATION 用户名 [ schema_element [ ... ] ]

    CREATE SCHEMA IF NOT EXISTS schema_name [ AUTHORIZATION user_name ]

    如果不存在授权用户名,则创建架构

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-11
      • 2018-10-24
      • 2020-02-20
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2021-04-01
      • 2011-12-29
      相关资源
      最近更新 更多