如何创建可以使用python脚本调用的postgresql函数?

时间:2014-10-22 01:09:21

标签: python postgresql pgadmin

我有一项任务,要求我从pgAdminIII中的表中提取多行,将行数据操作为几个新的行类型(或者只是以某种方式生成数据)。

因为实际操作似乎很难使用基本的sql命令,所以我决定尝试制作postgresql存储过程(或函数)。到目前为止,我所得到的只是语法错误。

我的postgresql功能:

CREATE FUNCTION getAllPayments(double precision, double precision, timestamp) RETURNS text AS $$
DECLARE
credLim ALIAS FOR $1;
paid ALIAS FOR $2;
pdate ALIAS FOR $3;
totalpayments double precision;
numberofpayments integer;
availablecredit double precision;
BEGIN
IF payments.customernumber = orders.customernumber THEN
	numberofpayments := COUNT(pdate);
	totalpayments := SUM(paid);
	availablecredit := credLim + totalpayments - numberofpayments;
SELECT customers.customername, customers.customernumber, credLim, availablecredit, totalpayments, numberofpayments from customers, payments;
ELSE
Return "failed attempt";
END IF;

END;

调用它的python脚本:

get_data = "getAllPayments(customers.creditlimit, payments.amount, payments.paymentdate)"
seperator = "---------------------------------------------------------------------------------"

crsr2 = conn.cursor()
crsr2.execute(get_data)

print('Customer Number   Customer Name   Payments Made   Value of Orders   Credit Limit   Available Credit')
print(seperator)
for x in crsr2:
    neu = str(x)
    w = neu.replace(', ', ',     ')
    print(w)
print(seperator)

1 个答案:

答案 0 :(得分:1)

我看到了

  

错误:在#34; $$

附近未接受美元引用的字符串

终止该字符串,并告诉dbms您正在使用哪种语言。

CREATE FUNCTION getAllPayments(double precision, double precision, timestamp) 
RETURNS text AS $$
DECLARE
    credLim ALIAS FOR $1;
    paid ALIAS FOR $2;
    pdate ALIAS FOR $3;
    totalpayments double precision;
    numberofpayments integer;
    availablecredit double precision;
BEGIN
    IF payments.customernumber = orders.customernumber THEN
        numberofpayments := COUNT(pdate);
        totalpayments := SUM(paid);
        availablecredit := credLim + totalpayments - numberofpayments;

        SELECT customers.customername, customers.customernumber, credLim, availablecredit, totalpayments, numberofpayments from customers, payments;

    ELSE
        Return "failed attempt";
    END IF;
END;
$$                   -- Terminate the string.
language plpgsql;    -- Identify the language.

那应该让它编译。我没有试着看它是否有意义,但我注意到了这条线

        availablecredit := credLim + totalpayments - numberofpayments;

看起来有点可疑,不使用ANSI连接通常是个坏主意。