2014-03-31 18 views
0

我使用PostgreSQL 8.4路由河網,下面是我的代碼在pgAdmin的輸入,結果是好的,如何使用Python來執行在PostgreSQL的SQL線?

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); 

enter image description here

我已經安裝了psycopg2併成功連接蟒蛇和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代碼?

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

回答

2

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

請注意,在SQL代碼

+0

非常感謝您使用Python中的三重引號和Dollar-quoted String Constants!這工作!現在我更瞭解sql! – Heinz

相關問題