Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I use postgresql 8.4 to route a river network, the following is my code typed in pgAdmin and the result is fine,

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

I have installed psycopg2 and it successfully connect python and postgresql,

#set up python and postgresql connection
import psycopg2

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

Now I need to directly execute my sql code on the top in pyscripter, how should I change these codes to python code?

I am working with postgresql 8.4, python 2.7.6 under Windows 8.1 x64.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Use the execute method of the cursor class to pass the parameters

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

Notice the use of triple quotes in Python and Dollar-quoted String Constants in the SQL code

share|improve this answer
    
thank you very much! This works! and now I know more about sql! –  Heinz Mar 31 at 12:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.