sqlvb.netrecord-count

ExecNonQuery SQL


VB.NET - Visual Studio 2017 Professional - Winforms

I am creating a SQL control class where by I can simply run a query from another form by typing:

SQL.ExecQuery("SELECT * FROM ...")

What I have so far works very well. However, I only get a record count back when I am doing a select query. When I do insert, update, or delete I do not get a record count back.

I know I have to use ExecuteNonQuery for those, but how do I write it into this method that I already have:

Public Sub ExecQuery(Query As String)
    ''Reset Query Statistics
    RecordCount = 0
    Exception = ""

        Try
            SQLCon.Open()

            ''Create SQL Command
            SQLCmd = New SqlCommand(Query, SQLCon)

            ''Load parameters into SQL Command
            Params.ForEach(Sub(x) SQLCmd.Parameters.Add(x))

            ''Clear paramater List 
            Params.Clear()

            ''Execute Command & fill dataset
            SQLDS = New DataSet
            SQLDA = New SqlDataAdapter(SQLCmd)
            RecordCount = SQLDA.Fill(SQLDS)

            SQLCon.Close()
        Catch ex As Exception
            ''Capture error
            Exception = "ExecQuery Error: " & vbNewLine & ex.Message
            MessageBox.Show(Exception, "SQL QUERY FAILED!", MessageBoxButtons.OK, MessageBoxIcon.Error)
            MessageBox.Show(Query)
        Finally
            ''Close Connection
            If SQLCon.State = ConnectionState.Open Then SQLCon.Close()
        End Try

End Sub

Can someone give me an example of how I can incorporate ExecuteNonQuery into this sub so that I can get a record count of the inserted, deleted or modified?


Solution

  • This always happens to me - I try to figure something out, I can't, I post the question, and within a few mins I figure out the answer! (Thanks for the push in the right direction!)

    From the above method, I changed this:

    ''Execute Command & fill dataset
            SQLDS = New DataSet
            SQLDA = New SqlDataAdapter(SQLCmd)
            RecordCount = SQLDA.Fill(SQLDS)
    

    to this:

     ''Execute Command
            RecordCount = SQLCmd.ExecuteNonQuery()
    

    Everything is now working as I would expect. I was not realizing that execnonquery will not work at all with any sort of dataset/datatable manipulation in the way I was using it.