|
This method of command object will add, update and delete records from the database. Th below code snipplet will demonstrate the use of ExecuteNonQuery().
Adding Records in the Database
The following are the steps involved in the operation.
- Create and Open the database connection
- Create the database statement
- Execute the command with the ExecuteNonQuery() method
/************ Code Snippet to Add record in the database***********/
Note:- This example will add new product to the database and its attributes like product name and price.
<%@ import namespace=”System.data.sqlclient”>
<%
Dim con as SqlConnection
Dim cmd as SqlCommand
Dim strInsert as String
con= new SqlConnection (“Data Source=localhost; initial catalog=Test; uid=sa; pwd=sa”)
strInsert=”Insert into tbl_Product (productName, price) values (“Testprod”,55)”
cmd= new SqlCommand (strInsert, con)
con.Open() //open the Connection
cmd.ExecuteNonQuery()
con.Close () // End of the connection
%>
Updating Database Record:
The process of updating the records in the database is same as we follow at the time of adding new record in the database. Here also we have to open the connection and then executing the command object and updating the record through its ExecuteNonQuery method.
/***************Update Record in Database *****************/
Note:- This will update lastname of the employee where the firstname is Dick This example using the connection with Ms Access
<%@ import namespace=”System.Data.Oledb”>
<%
Dim con as SqlConnection
Dim cmd as SqlCommand
Dim strUpdate as String
con= new OleDbConnection (“provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\TestDb.mdb”)
strUpdate=”update tblEmployee set lastname='dang' where firstname='Dick'”
cmd= new OledbCommand (strUpdate, con)
con.Open() //open the Connection
cmd.ExecuteNonQuery ()
con.Close() // End of the connection
%>
Deleting the Record from the Database:
Note:- Deleting the record will delete the matchable records from the database and if the record doesn't exist in the database it won't throw any error. The Example delete the record where the username=”vik”
/*************Delete the Record from the Database***********/
<%@ import namespace=”System.data.sqlclient”>
<%
Dim con as SqlConnection
Dim cmd as SqlCommand
Dim strDelete as String
con= new SqlConnection (“Data Source=localhost; initial catalog=TestDB; uid=sa;pwd=sa”)
strDelete=”delete from TblLogin where username='vik'”
cmd= new SqlCommand (strDelete, con)
con.Open () //open the Connection
cmd.ExecuteNonQuery()
con.Close() // End of the connection
%>
|