如何将列表值传递给SQL Select查询?

时间:2018-12-17 15:46:24

标签: python oracle list parameter-passing cx-oracle

SQL查询:

Select *
from table_name 
where ID in (123) 
  and date in (Select max(date) 
               from table_name 
               where ID in (123))

我想一次在上述SQL查询中一次传递下面提到的列表值,并为列表中的每个ID收集结果 软件包:cx_Oracle

我的尝试:

import cx_oracle
List= {123, 234,345,....}
List1 = []
query = " Select * from table_name where ID in (%s) 
     and date in (Select max(date) from table_name where ID in (%s))"

for j in List:
    cursor1 = db_ora.cursor()
    tb = cursor1.execute(query, params= List )
    for i in tb:
        List1.append(i)

预先感谢您,如果您需要我的更多帮助,请告诉我

2 个答案:

答案 0 :(得分:0)

据我所知,Oracle不会接受此类列表作为有效参数。将该值列表存储到单独的表中,然后将其用作查询的源,例如

Cold boot now

,或者在可能的情况下,将逗号分隔的字符串分成几行,例如

Private Sub TVMenu_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TVMenu.KeyPress
    If e.KeyChar = Chr(13) Then
        Select Case TVMenu.SelectedNode.Name
            Case Is = "nGuru"
                FmGuru.Close()
                FmGuru.TopLevel = False
                FmGuru.FormBorderStyle = Windows.Forms.FormBorderStyle.None
                FmGuru.WindowState = FormWindowState.Maximized
                PContent.Controls.Add(FmGuru)
                FmGuru.Show()
        End Select
    End If
End Sub

此外,我建议您在列名之前使用表别名,以免造成混淆。

答案 1 :(得分:0)

如果要使其与原始代码相似,可以使用字符串格式

Python 2

import cx_oracle
List= [123, 234,345,....]
List1 = []
masterQuery = " Select * from table_name where ID in (%s) 
     and date in (Select max(date) from table_name where ID in (%s))"

for j in List:
    cursor1 = db_ora.cursor()
    newQuery = masterQuery % (j, j)
    tb = cursor1.execute(newQuery)
    for i in tb:
        List1.append(i)

Python 3

import cx_oracle
List= [123, 234,345,....]
List1 = []
masterQuery = " Select * from table_name where ID in {} 
     and date in (Select max(date) from table_name where ID in {})"

for j in List:
    cursor1 = db_ora.cursor()
    newQuery = masterQuery.format(j, j)
    tb = cursor1.execute(newQuery)
    for i in tb:
        List1.append(i)