如何在选择查询中放置一个数组

时间:2013-04-23 05:27:40

标签: sql database vb6

我试图通过在Select查询中放置一个数组来填充gridview。每次我尝试这个我都会收到一个错误:运行时错误:3705“对象打开时不允许操作”。我理解为什么我会收到此错误,但有没有替代方法将数组放在select查询中。我正在使用的代码如下:

Public con1 As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim q As String
Dim i As Integer
Dim trainIds(30) As String
Public Sub con()
Set con1 = New ADODB.Connection
con1.Open ("tts123")
End Sub


Public Sub opentable(sql As String)
    Set rs = New ADODB.Recordset
    rs.Open sql, con1
End Sub


Private Sub Command1_Click()
    trainIds(0) = "HM2"
    trainIds(1) = "HM2"
    trainIds(2) = "HM1"
    For i = 0 To 2
          q = "Select * from TrainTable Where TrainId ='" & trainIds(i) & "'"
          rs.CursorType = adOpenStatic
          rs.CursorLocation = adUseClient
          rs.LockType = adLockOptimistic
          rs.Open q, con1
          If rs.RecordCount > 0 Then
              Set DataGrid1.DataSource = rs
          Else
                MsgBox "No record found "
                rs.Close
           End If
     Next
End Sub

Private Sub Form_Load()
      Set con1 = New ADODB.Connection
      con1.ConnectionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =   E:\VBnewProject\TrainTimeSchedule"
con1.Open ("dsn=tts123")
End Sub

1 个答案:

答案 0 :(得分:2)

您应该使用IN作为查询

Select * from TrainTable Where TrainId IN {List of train ids to check}

另外看看使用SqlParameter对象传递参数,您当前的代码可以打开SQL注入,查看this示例