Google

Wednesday, March 5, 2008

The insert command - VB.Net code and save to SQL Server 2005

A simple code on how to connect sql 2005 from VB.Net via SQL connection string, and the use of ExecuteNonQuery() method to execute the command and the try and catch to catch errors during runtime.

Example information:

SQL data:

Database name: user

Table name: user_t

Columns: user_id,lname,fname,username,password,usertype

Controls:

textboxes: textID = for Id

textlname = for last name

textfname = for first name

textusername = for user name

textpassword = for password

combobox: comboUsertype = for user type

Code:

Dim con As New SqlClient.SqlConnection

Dim strCon as string = "Data Source=MIKEL\SQLEXPRESS;Initial Catalog=user_t;Integrated Security=True"

Dim strCommand as string = “Insert into user_t (user_id, lname, fname, username, password, usertype) values (‘”& me.textID.text &”’,‘” & me.textlname.text &”’, ‘” &me.fname.text &”’, ‘”&me.textusername.text &”‘,‘”& me.textpassword.text &”’,‘”&me.comboUsertype.text &”’)”

Sub insert()

Try

con.ConnectionString = strCon

Dim cm As New SqlClient.SqlCommand(strCommand, con)

con.Open()

cm.ExecuteNonQuery()

MsgBox("Succesfully saved…")

Catch ex As Exception

MessageBox.Show(ex.Message, "Error")

Finally

If con.State = ConnectionState.Open Then

con.Close()

End If

End Try

End sub



No comments: