【问题标题】:How to execute sql lines in postgresql using python?如何使用python在postgresql中执行sql行?
【发布时间】:2014-10-15 23:36:39
【问题描述】:

我使用postgresql 8.4 路由河网,下面是我在pgAdmin 中输入的代码,结果很好,

select * from driving_distance
('select gid as id,
 start_id::int4 as source, end_id::int4 as target,
 shape_leng::double precision as cost from network',
 10, 1000000, false, false);

我已经安装了psycopg2,它成功连接了python和postgresql,

#set up python and postgresql connection
import psycopg2

try:
    conn = psycopg2.connect("dbname = 'routing_template' user = 'postgres' host = 'localhost' password = 'xxxxx'")
except:
    print 'I am unable to connect the database'

现在我需要直接在pyscripter的最上面执行我的sql代码,这些代码要怎么改成python代码呢?

我正在使用 Windows 8.1 x64 下的 postgresql 8.4、python 2.7.6。

【问题讨论】:

    标签: python string postgresql parameters psycopg2


    【解决方案1】:

    使用cursor类的execute方法传递参数

    import psycopg2
    
    query = """
        select *
        from driving_distance ($$
            select
                gid as id,
                start_id::int4 as source,
                end_id::int4 as target,
                shape_leng::double precision as cost
            from network
            $$, %s, %s, %s, %s
        )
    ;"""
    
    
    conn = psycopg2.connect("dbname=cpn")
    cur = conn.cursor()
    cur.execute(query, (10, 1000000, False, False))
    rs = cur.fetchall()
    conn.close()
    print rs
    

    注意 Python 中的三引号和 SQL 代码中 Dollar-quoted String Constants 的使用

    【讨论】:

    • 非常感谢!这行得通!现在我对sql有了更多的了解!
    猜你喜欢
    • 2022-01-27
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2015-08-11
    • 2016-11-04
    相关资源
    最近更新 更多