Pages

Saturday 12 January 2013

Explain Execute Non Query

ExecuteNonQuery
ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations. This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements.

Before implement this example first design one table UserInformation in your database as shown below
Column Name
Data Type
Allow Nulls
UserName
varchar(50)
Yes
LastName
varchar(50)
Yes
Location
Varchar(50)
Yes
Once table designed in database write the following code in your aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Example of ExecuteNonQuery in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /><br />
<b>Number of Rows Effected: </b><asp:Label ID="lblDetails" runat="server" />
</div>
</form>
</body>
</html>
Now add the following namespaces in code behind
C# Code
using System;
using System.Data.SqlClient;
After add namespaces write the following code in code behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con=new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into UserInformation(UserName,FirstName,LastName,Location) values(@Name,@FName,@LName,@Location)", con);
cmd.Parameters.AddWithValue("@Name", "Suresh Dasari");
cmd.Parameters.AddWithValue("@FName", "Suresh");
cmd.Parameters.AddWithValue("@LName", "D");
cmd.Parameters.AddWithValue("@Location","Chennai");
int result= cmd.ExecuteNonQuery();
if(result>=1)
{
lblDetails.Text =  result.ToString();
}
else
{
lblDetails.Text = "0" ;
}
con.Close();
}
}
VB.NET Code
Imports System.Data.SqlClient

Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("insert into UserInformation(UserName,FirstName,LastName,Location) values(@Name,@FName,@LName,@Location)", con)
cmd.Parameters.AddWithValue("@Name", "Suresh Dasari")
cmd.Parameters.AddWithValue("@FName", "Suresh")
cmd.Parameters.AddWithValue("@LName", "D")
cmd.Parameters.AddWithValue("@Location", "Chennai")
Dim result As Integer = cmd.ExecuteNonQuery()
If result >= 1 Then
lblDetails.Text = result.ToString()
Else
lblDetails.Text = "0"
End If
con.Close()
End Using
End Sub
End Class
Demo
If you observe above output whenever we click on button one new record inserting into table UserInformation and returning number records inserted.

No comments:

Post a Comment