08 May 2009

VB.Net code: ADO.Net – Insert a record to a table

'Insert a record into customer table
'note: CustomerID is nchar(5). Primary Key
Dim sql As String = "INSERT INTO Customers " & _
    "(CustomerID, CompanyName, ContactName, ContactTitle) " & _
    "VALUES ('" & strCustomerID & "','" & _
                         strCompanyName & "','" & _
                         strContactName & "','" & _
                         strContactTitle & "')"

Dim connStr As String = "server=localhost; uid=sa; password=myPassWord; database=Northwind"
Dim conn As SqlConnection = New SqlConnection(connStr)
Dim comm As SqlCommand = New SqlCommand(sql, conn)

conn.Open()
Dim intRowsAdded As Integer
intRowsAdded = comm.ExecuteNonQuery()
'You can use the ExecuteNonQuery to update/delete record too.

conn.Close()
conn = Nothing
comm = Nothing

You might need to modify the some VB code.  Example:
server=.\sqlexpress; uid=sa; pasword=wna05;
- for accessing MS SQL Express in the localhost

or, server=myComputerName\sqlexpress -depends on your notebook configuration

No comments: