0

我使用 pyscripter 从外部调用 PostgreSQL 并路由我的网络,这是我的代码,

import sys, os

#set up psycopg2 environment
import psycopg2

#driving_distance module
query = """
    select *
    from driving_distance ($$
        select
            gid as id,
            source::int4 as source,
            target::int4 as target,
            cost::double precision as cost
        from network
        $$, %s, %s, %s, %s
    )
"""

#make connection between python and postgresql
conn = psycopg2.connect("dbname = 'TC_area' user = 'postgres' host = 'localhost' password = 'xxxx'")
cur = conn.cursor()

#count rows in the table
cur.execute("select count(*) from network")
result = cur.fetchone()
k = result[0] + 1                #number of points = number of segments + 1

#run loops
rs = []
i = 1
while i <= k:
    cur.execute(query, (i, 1000000, False, True))
    rs.append(cur.fetchall())
    i = i + 1

#import csv module
import csv

j = 0
h = 0
ars = []
element = list(rs)

#export data to every row
with open('distMatrix.csv', 'wb') as f:
    writer = csv.writer(f, delimiter = ',')
    while j <= k - 1:
        while h <= k - 1:
            rp = element[j][h][1]
            ars.append(rp)
            h = h + 1
        else:
            h = 0
            writer.writerow(ars)
            ars = []
        j = j + 1

conn.close()

结果是好的,但是如果我想在PostgreSQL中的函数driving_distance中使用reverse_cost函数,我只需在'cost::double precision as cost'下面添加一行,

rcost::double precision as reverse_cost

添加此行后弹出此错误框,

在此处输入图像描述

以及 python IDLE 中的错误消息,

Traceback (most recent call last):


File "C:\Users\Heinz\Documents\pyscript\postgresql\distMatrix.py.py", line 47, in <module>
    cur.execute(query, (i, 1000000, False, True))
ProgrammingError: 錯誤:  在"語法錯誤"附近發生 rcost
LINE 7:             rcost::double precision as reverse_cost
                    ^
QUERY:  
        select
            gid as id,
            source::int4 as source,
            target::int4 as target,
            cost::double precision as cost
            rcost::double precision as reverse_cost
        from network

PS。我已经更改了这个网络的表格,因此它确实有一个“rcost”列,这是视图的一部分,

在此处输入图像描述

如果我在 pgAdmin 中执行代码,我可以成功地得到正确的结果,

SELECT * FROM driving_distance('
SELECT gid as id,
    source::int4 AS source, 
    target::int4 AS target,
    cost::double precision as cost,
    rcost::double precision as reverse_cost
    FROM network',
3, 10000000, false, True);

在此处输入图像描述

但是我需要python来做循环,这个问题怎么解决?</p>

PS。如果我将函数中的两个布尔值都设置为 FALSE,理论上程序将忽略 rcost 并返回仅从成本计算的答案,但我仍然遇到相同的错误,

在此处输入图像描述

这个问题似乎是由rcost 引起的。

我在 Windows 8.1 x64 下使用 PostgreSQL 8.4、python 2.7.6。


更新#1

我在脚本中更改了 2 行,然后它就可以工作了,

cost::double precision as cost,                    #need to add a trailing comma if followed by rcost

cur.execute(query, (i, 100000000000, False, True)) #the range must be greater than max of rcost
4

1 回答 1

0

您的行“cost::double precision as cost”需要一个尾随逗号。

于 2014-04-17T13:48:52.377 回答