Link to home
Start Free TrialLog in
Avatar of ljhodgett
ljhodgett

asked on

Execute insert sql statement in vb.net 2005

Hi,

I am trying to get to grips with vb.net and sql server.  I have managed to retrieve data into a dataset like I would in vb6 but using record sets but I am not too sure how to execute an insert statement as obviously it doesn't need a dataset. The code I have used for the dataset is: -

Public Class frmAddProduct
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        On Error GoTo error_Handler

        Dim ds As New DataSet
        Dim sql As String
        sql = "Select * from Customers"
        dbOpen()
        Dim da As New SqlClient.SqlDataAdapter(sql, oConn)
        da.Fill(ds, "Customers")
        DataGridView1.DataSource = ds.Tables("Customers")

error_Handler:
        If Err.Number <> 0 Then
            MsgBox("An error has occured while connecting to the SQL Server. Error no: " & Err.Number & vbCrLf & vbCrLf & "Description:" & vbCrLf & Err.Description)
            dbClose()
            End
        End If

        MsgBox("Success")
        dbClose()
    End Sub
End Class

Best Regards
Lee
ASKER CERTIFIED SOLUTION
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium 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
CreateCommand ("insert into <table> values (1,2,3) ", "Driver={SQL Server};Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;")
Unlike ASO, the connection object in ADO.net doesn't have the execute method to execute a query. However th command object has a similar method called ExecuteNonQuery. You can use this method to execute your insert statement.
Oops..Dhaest types faster :-))
Avatar of Sancler
Sancler

How are you creating the new record that you want to insert?  Because, if it created in the datatable, or created in a bound control and so gets into the datatable, you would be able to use the dataadapter to do the insert.  Have a look at the last post in this thread

https://www.experts-exchange.com/questions/22048420/dataadapter-datagridview.html

Although it's coded for OleDb it is just applicable, with the terminology changed, to SQL

Roger