如何使用excel创建参数化查询? (VB.NET)

时间:2016-08-15 20:23:58

标签: vb.net excel

我尝试使用参数化查询在Excel工作表中运行更快的更新子句...但是当尝试这样做时,vb.net说&#34;操作必须使用可更新的查询&#34;。< / p>

使用连接进行常规查询时,查询有效:

 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

但是当我尝试这种方式时,查询不起作用......(&#34;操作必须使用可更新的查询&#34;)

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]=@dato WHERE [@columna]=@itm"
        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 个答案:

答案 0 :(得分: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 & "]=@dato WHERE [" & columna & "]=@itm"
    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