簡體   English   中英

如何使用python在postgresql中執行sql行?

[英]How to execute sql lines in postgresql using python?

我使用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。

使用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代碼中使用Python中的三引號和引用美元引用的字符串常量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM