Is it possble to insert a python function into SQL query

时间:2015-10-06 09:06:18

标签: python sql postgresql

I am trying to write a case statement in SQL that says if 2 parameters past then do this if 3 then that...

I tried to use len(xyz) I know why my code is wrong but I am not sure how to achieve this... else I'll have to write less compact code with if statements on the outside

LocAll = ('RSA','EC','Grahamstown')

 """SELECT * 
    FROM User_Skills US, User_Profile UP 
    WHERE US.UserId = UP.UserId

    CASE WHEN len{0} = {1} THEN 
    UP.country = {2} 
    AND UP.state= {3} 
    AND UP.city= {4}


    """.format(LocAll, 3,LocAll[0],LocAll[1],LocAll[2]) ) 

Thank you

As suggested in the comments I used {0} and placed the function in the .format as (len(LocAll)....)

 """SELECT *, 

        CASE WHEN {0} = {1} 
        THEN 

            WHERE 
            US.UserId = UP.UserId AND
            UP.country = {2} 
            AND UP.state= {3} 
            AND UP.city= {4} 
        END 

        FROM User_Skills US, User_Profile UP       

    """.format(len(LocAll), 3,LocAll[0],LocAll[1],LocAll[2]) )

However I get an syntax error?

2 个答案:

答案 0 :(得分:0)

WHERE表达式更改为有效的CASE语法:

LocAll = ('RSA','EC','Grahamstown')

 """SELECT
        * 
    FROM 
        User_Skills US, User_Profile UP 
    WHERE 
        US.UserId = UP.UserId
        AND
        1 = CASE WHEN 
                {0} = {1} 
                AND UP.country = {2} 
                AND UP.state= {3} 
                AND UP.city= {4}
            THEN 1 ELSE 0 END

""".format(len(LocAll), 3, LocAll[0], LocAll[1], LocAll[2]) ) 

答案 1 :(得分:0)

只需打印出来并检查替换产生的字符串:你会得到像

这样的东西
           UP.country = RSA

看到了吗?由于RSA是一个字符串,因此您需要在其周围添加引号:

           UP.country = '{}'

但是使用"准备好的陈述"会好得多。并让您的数据库模块替换您 - 否则您的代码将在您第一次搜索包含单引号的字符串时再次崩溃。也许你确实打算使用准备好的声明?您的代码只是使用python的常规字符串替换。