postgresql 使用python - Select语句将元组插入postegresql

fdbelqdn  于 2022-12-03  发布在  PostgreSQL
关注(0)|答案(1)|浏览(135)

你好,我正在尝试用python插入到一个pgadmin表,我用了execute,它工作了,但是对于我的第二个aprt,我需要使用一个函数,我得到了一切工作,除了用select插入,它告诉我语法错误,或者忘记了逗号,字面上的一切。我是新的,所以帮助将是apprecipated。

def insrtDirector(q,w,e,r,t,y,u):
        sql1 = (q,w,e,r,t,y,u)
        insrt = """INSERT INTO "Director" VALUES (%s,%s,%s,%s,%s,%s,%s)"""
        cur.execute(insrt,sql1)
    insrtDirector(uuid.uuid4(), (SELECT "UName" from University WHERE "UName" = 'University College London') , (SELECT "DName" from Department WHERE "DName" ='English') , 'Christopher (3)', 'Nolan (3)', 1970, 'Westminster, London, United Kingdom' )

错误

insrtDirector(uuid.uuid4(), (SELECT "UName" from University WHERE "UName" = 'University College London') , (SELECT "DName" from Department WHERE "DName" ='English') , 'Christopher (3)', 'Nolan (3)', 1970, 'Westminster, London, United Kingdom' )
                                        ^^^^^^^
SyntaxError: invalid syntax
oprakyz7

oprakyz71#

你需要正确地使用子查询(google它!)。尝试这样的东西,它可能会工作(请修复您的变量名,qwertyu是不好的,应该是描述性的,如unique_id,uname,dname,first_name,等等)

def insrtDirector(q,w,e,r,t,y,u):
    # Assume w and e are always subqueries with one result
    # Also assume no outside source can supply w and e (must be sanitized to not be subject to sql injection)
    insrt = "INSERT INTO Director VALUES (%s,{uname_subquery},{dname_subquery},%s,%s,%s,%s)".format(
        uname_subquery=w,
        dmane_subquery=e,
    )
    # This print command is just temporary so you can see what it looks like
    print("insert command:", insrt)
    sql1 = (q,r,t,y,u)
    cur.execute(insrt, sql1)

insrtDirector(
    uuid.uuid4(),
    "(SELECT UName from University WHERE UName = 'University College London')",
    "(SELECT DName from Department WHERE DName = 'English')",
    'Christopher (3)',
    'Nolan (3)',
    1970,
    'Westminster, London, United Kingdom',
)

相关问题