通过psycopg2创建连锁查询

时间:2016-05-23 10:48:28

标签: python postgresql psycopg2

我正在使用psycopg2和Python来查询PostGIS数据库中的表。这是我为了排除列而构建的查询:the_geom

sqlstr = "SELECT 'SELECT ' || ARRAY_TO_STRING(ARRAY(SELECT COLUMN_NAME::VARCHAR(50) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{table}' AND COLUMN_NAME NOT IN ('the_geom') ORDER BY ORDINAL_POSITION), ', ') || ' FROM {table}';".format(** {
    'table': name
})

cur.execute(sqlstr)
sqlstr = cur.fetchall()
print(sqlstr)

返回此内容:

SELECT fid, FS2011, NAME_1, Admin1, ANUAK, SIDAMO, BAGIRMI, BAKOMO, KOMA, KARAMOJO, SOUTHERN_L, DAGO, DINKA, ACHOLI, MURLE, LOTUKO, Area_m2, BARI_pc, SUDARAB_pc, SEREMUN_pc, AZANDE_pc, BANDA_pc, MORUMANGpc, NUER_pc, ANUAK_pc, TES_pc, SIDAM_pc, BERTA_pc, NORTH_L_pc, BAGRIMI_pc, BAKOMO_pc, KOMA_pc, KARAMOJOpc, SOUTJ_L_pc, DAGO_pc, DINKA_pc, ACHOLI_pc, MURLE_pc, LOTUK_pc, MAJORITY FROM ssd_ethnicitystatstics_adm1'

问题是列名称原来是资本。出于这个原因,我需要在每个列名称周围包含引号。为此,我将查询修改为:

sqlstr = "SELECT 'SELECT ' || ARRAY_TO_STRING(ARRAY(SELECT ('"' || COLUMN_NAME::VARCHAR(50) || '"') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='{table}' AND COLUMN_NAME NOT IN ('the_geom') ORDER BY ORDINAL_POSITION), ', ') || ' FROM {table}';".format(** {
    'table': name
})

这将返回错误:

ProgrammingError: could not find array type for data type unknown

它必须与Python和psycopg2中的引号相关。

1 个答案:

答案 0 :(得分:1)

使用三重引号:

sqlstr = """
    SELECT
        'SELECT ' ||
        ARRAY_TO_STRING(ARRAY(
            SELECT ('"' || COLUMN_NAME::VARCHAR(50) || '"')
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME='{table}' AND COLUMN_NAME NOT IN ('the_geom')
            ORDER BY ORDINAL_POSITION
        ), ', ') ||
        ' FROM {table}';
""".format(** {'table': name})