2016-08-15 67 views
0

我試圖使用參數化查詢來運行更快的Excel表單中的更新子句......但是當試圖做,vb.net說「操作必須使用可更新的查詢」。如何使用excel創建參數化查詢? (VB.NET)

與串連定期查詢,查詢的工作原理:

Protected Friend Sub reemplazarDato(ByVal columna As String, ByVal dato As String, ByVal con As String) 
    Dim cmd As String = "" 
    conexion.Open() 
    For Each itm In arrayErrores 
     cmd = "UPDATE [" & obtenerHojaActual(columna, con) & "$] SET [" & columna & "]='" & dato & "' WHERE [" & columna & "]='" & itm & "'" 
     Try 
      Dim comando As New OleDbCommand(cmd, conexion) 
      comando.ExecuteNonQuery() 
      comando.Dispose()    
     Catch ex As Exception 
      repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog() 
     End Try 
    Next 
    conexion.Close() 
End Sub 

但是當我嘗試這種方式,查詢不工作...(「操作必須使用一個可更新的查詢」)

Protected Friend Sub reemplazarDato(ByVal columna As String, ByVal dato As String, ByVal con As String) 
    Dim cmd As String = "" 
    Dim hoja As String = obtenerHojaActual(columna, con) 
    Dim comando As New OleDbCommand 
    comando.Connection = conexion 
    conexion.Open() 
    For Each itm In arrayErrores 
     cmd = "UPDATE [" & hoja & "$] SET [@columna][email protected] WHERE [@columna][email protected]" 
     comando.CommandText = cmd 
     comando.Parameters.Add("@columna", OleDbType.VarChar, columna.Length).Value = columna 
     comando.Parameters.Add("@dato", OleDbType.VarChar, dato.Length).Value = dato 
     comando.Parameters.Add("@itm", OleDbType.VarChar, itm.ToString.Length).Value = itm 
     Try 
      comando.ExecuteNonQuery() 
      comando.Parameters.Clear() 
     Catch ex As Exception 
      repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog() 
     End Try 
    Next 
    conexion.Close() 
    comando.Dispose() 
End Sub 

我如何用excel來做到這一點?

+1

我不相信它是有效的SQL參數化的列名 - 即'columna'需要使用字符串連接作爲你的第一個代碼塊來設置,而不是作爲一個參數。 – Mark

+0

謝謝馬克,那是問題:( – TwoDent

回答

1

參數化列名無效 - 即columna需要像在第一個代碼塊中那樣使用字符串連接來設置,而不是作爲參數。此外,您不需要爲每次迭代定義SQL和命令參數 - 只需定義一次並在每次循環中設置值。

Protected Friend Sub reemplazarDato(ByVal columna As String, ByVal dato As String, ByVal con As String) 
    Dim hoja As String = obtenerHojaActual(columna, con) 
    Dim comando As New OleDbCommand 
    comando.Connection = conexion 
    comando.CommandText = "UPDATE [" & hoja & "$] SET [" & columna & "][email protected] WHERE [" & columna & "][email protected]" 
    comando.Parameters.Add("@dato", OleDbType.VarChar, dato.Length) 
    comando.Parameters.Add("@itm", OleDbType.VarChar, itm.ToString.Length) 
    conexion.Open() 
    For Each itm In arrayErrores 
     comando.Parameters("@dato").Value = dato 
     comando.Parameters("@itm").Value = itm 
     Try 
      comando.ExecuteNonQuery() 
     Catch ex As Exception 
      repairmanMessage("Error inesperado", ex.Message, My.Resources._error).ShowDialog() 
     End Try 
    Next 
    conexion.Close() 
    comando.Dispose() 
End Sub