psycopg2 无法执行多个查询
psycopg2 cannot execute multiple queries
我在使用 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))
来自文档的一些帮助:
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
我在使用 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))
来自文档的一些帮助:
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