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



Tuesday, March 4, 2008

Basic insert, delete, update command in SQL

Hi... these are just a basic insert, delete, and update command in database SQL (200, 2005) .

Example data

Database name: user

Table name: user_t

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

____________________________________________________________________________

Insert command

Insert into user_t (user_id, lname, fname, username, password, usertype) values (@parameter1, @parameter2, @parameter3, @parameter4, @parameter5, @parameter6)

It means, @parameter1 is a value that points to user_id, @parameter2 points to lname and so on…..

Update command

Update user_t set lname = @parameter1, fname = @parameter2, username = @parameter3, password = @parameter4, usertype = @parameter5 where user_id like @parameter6

Delete command

Delete from user_t where user_id like @parameter1

To download SQL server 2005 express edition and .Net framework 2.0 click here.

To download Visual Studio 2005 click here.