Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
ExecuteScalar Vs ExecuteNonQuery
WhatsApp
Suresh Paldia
14y
210.6
k
0
4
25
Blog
ExecuteScalar Method
Namespace:
System.Data.SqlClient
Return DataType
: System.Object (returns a single value)
Use :
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Example:
public int getSomeProdId()
{
int
count
=0;
SqlConnection
conn
=
new
SqlConnection(
connString
))
String
sqlQuery
=
"SELECT COUNT(*) FROM dbo.region";
SqlCommand
cmd
=
new
SqlCommand(
sqlQuery
,
conn
);
try
{
conn
.Open();
//Since return type is System.Object, a typecast is must
count
= (Int32)cmd.ExecuteScalar();
}
catch
(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
return
count
;
}
ExecuteNonQuery Method
Namespace:
System.Data.SqlClient
Return DataType
: System.Int32 (number of rows affected)
Use :
You can use the
ExecuteNonQuery
to perform catalog operations by executing UPDATE, INSERT, or DELETE statements.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1.
Example:
public void UpdateEmployeeEmail()
{
SqlConnection
conn
=
new
SqlConnection(
connString
))
String
sqlQuery
=
"UPDATE Employee SET empemail='
[email protected]
' WHERE empid=4;
SqlCommand
cmd
=
new
SqlCommand(
sqlQuery
,
conn
);
try
{
conn
.Open();
cmd.ExecuteNonQuery();
}
catch
(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
return
count
;
}
--------------------------------------------------------------------------------
Thank You...
ExecuteScalar Vs ExecuteNonQuery
Up Next
ExecuteReader, ExecuteNonQuery and Executescalar in ADO.NET
Ebook Download
View all
Printing in C# Made Easy
Read by 22.3k people
Download Now!
Learn
View all
Membership not found