如何从多个表中选择两列

时间:2014-04-29 21:44:20

标签: postgresql python

我想使用psycopg从多个表中选择两列。虽然join或union可能会为此目的而工作,但我正在寻找可以一次读取更多表的方法。

我的想法是首先获取表列表,然后使用循环按顺序读入每个表。但是,它不起作用。还有其他任何提示或想法吗?

这是我的代码。

try:
    con = psycopg2.connect(database='****', user='****', password = '****', host='****', port = ****)
    con.autocommit = True
    cur = con.cursor()
    cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name ASC;")
    tablename=cur.fetchall()


    for x in tablename:
        cur.execute("SELECT column1, column2 FROM %s ORDER BY column1 ASC", (x))
        mytest = cur.fetchall()

except psycopg2.DatabaseError, e:
if con: 
    con.rollback()

print 'Error %s' % e    
sys.exit(1)


finally: 

if con:
        con.close()

以下是错误消息。

Error syntax error at or near "'table1'"

LINE 1: SELECT column1, column2 FROM 'table1' ORDER BY ...

                                 ^

1 个答案:

答案 0 :(得分:0)

抱歉!我的错!我找到了解决方案。

对于postgresql代码中的字符串替换,python字符串应该是绝对清晰的,没有任何格式,如“”或“”。

以下是修订后的代码。

try:
    con = psycopg2.connect(database='****', user='****', password = '****', host='****', port = ****)
    con.autocommit = True
    cur = con.cursor()
    cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name ASC;")
    tablename=cur.fetchall()


    for x in tablename:
        for y in x:
            cur.execute("SELECT column1, column2 FROM {mytable} ORDER BY column1 ASC". format(mytable=y))
            mytest = cur.fetchall()

except psycopg2.DatabaseError, e:
    if con: 
        con.rollback()

    print 'Error %s' % e    
    sys.exit(1)


finally: 

    if con:
            con.close() 

再次感谢您的帮助!

相关问题