Python:如何将SQL查询输入为没有错误的字符串?

时间:2018-11-19 23:58:23

标签: python

我正在创建一个处理SQL查询的程序。目前,这非常简单,我要做的就是定义一个变量,并将其中的SQL语句定义为字符串。

E.G。

str = "SELECT DISTINCT 
pv.project_id,
gps.period_name,
gps.period_year,
rbse.resource_source_id,
rbse.alias as resource_name,
DECODE(pjo_plan_version_utils.get_time_phased_code(pv.plan_version_id), 'G', 
       pld.quantity, pjo_plan_version_utils.spread_amount('L', pld.start_date, pld.end_date, gps.start_date, gps.end_date, pld.quantity)
) as hours,
(131.4-pld.quantity)/131.4 unallocated_percentage
FROM
    pjf_rbs_elements rbse,
    gl_period_statuses gps,
    pjo_plan_line_details pld,
    pjo_planning_elements pe,
    pjo_plan_versions_vl pv,
    pjo_plan_types_vl pt
WHERE
    1=1
    AND pe.rbs_element_id = rbse.rbs_element_id 
    AND pld.planning_element_id = pe.planning_element_id 
    AND pv.plan_version_id = pe.plan_version_id
    AND pv.current_plan_status_flag = 'Y'
    AND ((gps.start_date <= pld.end_date)
    AND (gps.end_date >= pld.start_date))
    AND gps.adjustment_period_flag = 'N'
    AND gps.application_id = 10037
    AND pv.plan_type_id = pt.plan_type_id
    AND pt.plan_type_code = 'PROJECT_PLAN'"

我收到了无效的语法错误,因此显然我没有正确定义它。做这个的最好方式是什么?为了深入了解,该脚本将分析str以确定表和列,并返回与列表匹配的任何内容。

2 个答案:

答案 0 :(得分:1)

您的字符串连接不正确。

尝试这样的事情:

str = "line1" \
      "line2" \
      "line3" 

#output : no spaces or new lines
line1line2line3

或(但您不能通过以下方式进行缩进,如果缩进,则缩进将成为串联的一部分)

str = """line1
line2
line3"""

#output : new lines
line1
line2
line3

答案 1 :(得分:1)

多行中的字符串,因此您需要使用三重引号,否则您将获得EOL。另外,您不应该命名变量str,因为它已经是一个函数。

string = """SELECT DISTINCT 
pv.project_id,
gps.period_name,
gps.period_year,
rbse.resource_source_id,
rbse.alias as resource_name,
DECODE(pjo_plan_version_utils.get_time_phased_code(pv.plan_version_id), 'G', 
       pld.quantity, pjo_plan_version_utils.spread_amount('L', pld.start_date, pld.end_date, gps.start_date, gps.end_date, pld.quantity)
) as hours,
(131.4-pld.quantity)/131.4 unallocated_percentage
FROM
    pjf_rbs_elements rbse,
    gl_period_statuses gps,
    pjo_plan_line_details pld,
    pjo_planning_elements pe,
    pjo_plan_versions_vl pv,
    pjo_plan_types_vl pt
WHERE
    1=1
    AND pe.rbs_element_id = rbse.rbs_element_id 
    AND pld.planning_element_id = pe.planning_element_id 
    AND pv.plan_version_id = pe.plan_version_id
    AND pv.current_plan_status_flag = 'Y'
    AND ((gps.start_date <= pld.end_date)
    AND (gps.end_date >= pld.start_date))
    AND gps.adjustment_period_flag = 'N'
    AND gps.application_id = 10037
    AND pv.plan_type_id = pt.plan_type_id
    AND pt.plan_type_code = 'PROJECT_PLAN'"""