Link to home
Start Free TrialLog in
Avatar of Murray Brown
Murray BrownFlag for United Kingdom of Great Britain and Northern Ireland

asked on

VB.net SqlClient insert query

Hi

I am using the following code to insert a record into an online
SQL database. The MsgBox reads
"Records Inserted 1"
Is this a good way to check if the insert was successful?
If it isn't successful would should I expect?
If this isn't a good way is there a better way?
Thanks
Sub oInsert()
        Dim ra As Integer
     
        Dim oDate As String = "03/03/2011" 'Date.Now.ToString
        Dim oText As String = "sqlclient"
        Dim oNumber As Decimal = 100
        myConnection.Open()
        Dim sSQL As String
        sSQL = "Insert Into Table1 ([oDate],[oText], [oNumber]) Select '" & oDate & "' as Expr1, '" & oText & "' as Expr2, " & oNumber & " as Expr3"
        myCommand = New SqlCommand(sSQL, myConnection)
        ra = myCommand.ExecuteNonQuery()
        'Since no value is returned we use ExecuteNonQuery
        MsgBox("Records Inserted " & ra)

        myConnection.Close()
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gerwin Jansen
Gerwin Jansen
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Murray Brown

ASKER

Thanks. Just wanted to confirm that
This is the recommended way, but you should add an error trap around everything you do on the server.

A lot of things can happen when you communicate with a server, so you should be prepared for it. As a minimum, the following:

Try
      myConnection.Open()
        Dim sSQL As String
        sSQL = "Insert Into Table1 ([oDate],[oText], [oNumber]) Select '" & oDate & "' as Expr1, '" & oText & "' as Expr2, " & oNumber & " as Expr3"
        myCommand = New SqlCommand(sSQL, myConnection)
        ra = myCommand.ExecuteNonQuery()
Catch ex As SqlException
        MessageBox.Show("The following error occured while insterting the record: " & ex.Message)
        'Handle errors
End Try