Search code examples
vb.netoledboledbcommand

Can I pass a parameter of an OledbCommand to other OledbCommand?


This might be silly question but I need some solution in it.
I've done like

cmd.CommandText = "Insert Table1(Col1,Col2,Col3,Date) Values (1,'aa',101,?)"
cmd.Connection = con2
cmd.Parameters.AddWithValue("@Date", transdate)
ExecuteQuery(con2,cmd)

I wrote below code to avoid writing Using.. End Using everywhere.
Query runs fine if it has no parameter.

Private Sub ExecuteQuery(con as OledbConnection,cmd as OledbCommand)
Using con1 As New OleDbConnection(con.ConnectionString)
    Using cmd1 As New OleDbCommand(cmd.CommandText)
        cmd1.Connection = con1
        con1.Open()
        cmd1.ExecuteNonQuery()
        con1.Close()
    End Using
End Using

It works fine with parameters when I write cmd under Using Block.
But as I said, I am avoiding writing Using everywhere.
But doing like this gives error -- No Given values for one or more required parameters.


Solution

  • You need to adjust your ExecuteQuery because it's making a new command and losing the Parameters. Change it so that it uses the existing command you passed, and disposes it, or transfer the Parameters from your inbound command to the new one

    Private Sub ExecuteQuery(con as OledbConnection, cmd as OledbCommand)
      Using con1 As New OleDbConnection(con.ConnectionString)
        Try
            cmd.Connection = con1
            con1.Open()
            cmd.ExecuteNonQuery()
            con1.Close()
        Finally
            cmd.Dispose()
        End Try
      End Using 
    End Sub
    
    Private Sub ExecuteQuery(con as OledbConnection,cmd as OledbCommand)
      Using con1 As New OleDbConnection(con.ConnectionString)
        Using cmd1 As New OleDbCommand(cmd.CommandText)
            cmd1.Connection = con1
            ForEach p as Parameter in cmd.Parameters
              cmd1.Parameters.Add(p) 
            con1.Open()
            cmd1.ExecuteNonQuery()
            con1.Close()
        End Using
      End Using
    End Sub
    

    If you're looking for a way to make your db life easier check out Dapper or Entity Framework - you work with objects, it writes all the sql for you. This isn't a cessation of control (you still write the queries) it's delegating the boring aspects of executing your query, going through the results, digging out each text or int and assigning it to your user object's name or age..

    If you get to a point where you don't want to write the SQLs either, use Entity Framework, as it can convert between your objects and the db automatically