SlideShare a Scribd company logo
1 of 4
Download to read offline
1.Difference between ExecuteNonQuery() and ExecuteScalar() methods in ADO.NET

      S.No   ExecuteNonQuery()                  ExecuteScalar()

      1      It will work with Action Queries It will work with Non-Action Queries
             only                              that contain aggregate functions.
             (Create,Alter,Drop,Insert,Update,
             Delete).

      2      It returns the count of rows It returns the first row and first column
             effected by the Query.       value of the query result.

      3      Return type is int                 Return type is object.

      4      Return value is optional and can Return value is compulsory and should
             be assigned to an integer variable. be assigned to a variable of required
                                                 type.


Example-1 for ExecuteNonQuery Method -Insert:

SqlCommand cmd = new SqlCommand("Insert Into SampleTable Values('1','2')",con);
//con is the connection object

con.Open();
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed

Example-2 for ExecuteNonQuery Method - Update:

public void UpdateEmployeeEmail()
{
     SqlConnection conn = new SqlConnection(connString))
     String sqlQuery = "UPDATE Employee SET empemail='umar.ali@xyz.com' WHERE
empid=5;
     SqlCommand cmd = new SqlCommand(sqlQuery, conn);
     try
     {
        conn.Open();
        cmd.ExecuteNonQuery();
     }
     catch (Exception ex)
     {
        Console.WriteLine(ex.Message);
     }
      finally
      {
        conn.Close();
      }
      return count;
}
Example-1 for ExecuteScalar Method:

This returns only one value that is first column value of the first row in the executed query

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;
}


Example-2 for ExecuteScalar Method:

This returns one value only, no recordsets.

cmd.CommandText = "Select Name, DOB, from Emp where ID=1";
Dim strName As string = cmd.ExecuteScalar.ToString


2.Difference between ExecuteNonQuery() and ExecuteReader() methods in ADO.NET


       S.No    ExecuteNonQuery()                     ExecuteReader()

       1       It will work with Action Queries It will work with Action and Non-
               only                              Action Queries (Select)
               (Create,Alter,Drop,Insert,Update,
               Delete).

       2       It returns the count of rows It returns the collection of rows
               effected by the Query.       selected by the Query.

       3       Return type is int                    Return type is DataReader.

       4       Return value is optional and can Return value is compulsory and should
be assigned to an integer variable.   be assigned to an another object
                                                    DataReader.

Example-1 for ExecuteNonQuery Method -Insert:

SqlCommand cmd = new SqlCommand("Insert Into SampleTable Values('1','2')",con);
//con is the connection object

con.Open();
cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed

Example-2 for ExecuteNonQuery Method - Update:

public void UpdateEmployeeEmail()
{
     SqlConnection conn = new SqlConnection(connString))
     String sqlQuery = "UPDATE Employee SET empemail='umar.ali@xyz.com' WHERE
empid=5;
     SqlCommand cmd = new SqlCommand(sqlQuery, conn);
     try
     {
        conn.Open();
        cmd.ExecuteNonQuery();
     }
     catch (Exception ex)
     {
        Console.WriteLine(ex.Message);
     }
      finally
      {
        conn.Close();
      }
      return count;
}

Example for ExecuteReader Method:

Here, ExecuteReader is used to get set of records by specified query, namely, "select * from emp"

SqlConnection con = new SqlConnection(constr); //constructor can be connection of string.
SqlCommand cmd = new SqlCommand ("select * from emp", con);
con.Open();
SqlDataReader dr = cmd. ExecuteReader (CommandBehavior. CloseConnection); //Implicitly
closes the connection because CommandBehavior. CloseConnection was specified.

while(dr.Read())
{
Console.WriteLine (dr.GetString(0));
}
dr.Close();
And, further updates on difference between questions and answers, please visit my blog @
http://onlydifferencefaqs.blogspot.in/

More Related Content

Viewers also liked

Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Alberto Naranjo
 
Html interview-questions-and-answers
Html interview-questions-and-answersHtml interview-questions-and-answers
Html interview-questions-and-answersMohitKumar1985
 
Dotnet difference questions and answers compiled- 1(updated-2)
Dotnet difference questions and answers compiled- 1(updated-2)Dotnet difference questions and answers compiled- 1(updated-2)
Dotnet difference questions and answers compiled- 1(updated-2)Umar Ali
 
Multiple choice questions with answers
Multiple choice questions with answersMultiple choice questions with answers
Multiple choice questions with answersClassic Tech
 

Viewers also liked (7)

Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Javascript quiz
Javascript quizJavascript quiz
Javascript quiz
 
Html interview-questions-and-answers
Html interview-questions-and-answersHtml interview-questions-and-answers
Html interview-questions-and-answers
 
Dotnet difference questions and answers compiled- 1(updated-2)
Dotnet difference questions and answers compiled- 1(updated-2)Dotnet difference questions and answers compiled- 1(updated-2)
Dotnet difference questions and answers compiled- 1(updated-2)
 
Javascript Question
Javascript QuestionJavascript Question
Javascript Question
 
Multiple choice questions with answers
Multiple choice questions with answersMultiple choice questions with answers
Multiple choice questions with answers
 
Bit%20 ch02
Bit%20 ch02Bit%20 ch02
Bit%20 ch02
 

More from Umar Ali

Difference between wcf and asp.net web api
Difference between wcf and asp.net web apiDifference between wcf and asp.net web api
Difference between wcf and asp.net web apiUmar Ali
 
Difference between ActionResult() and ViewResult()
Difference between ActionResult() and ViewResult()Difference between ActionResult() and ViewResult()
Difference between ActionResult() and ViewResult()Umar Ali
 
Difference between asp.net mvc 3 and asp.net mvc 4
Difference between asp.net mvc 3 and asp.net mvc 4Difference between asp.net mvc 3 and asp.net mvc 4
Difference between asp.net mvc 3 and asp.net mvc 4Umar Ali
 
Difference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvcDifference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvcUmar Ali
 
Difference between asp.net web forms and asp.net mvc
Difference between asp.net web forms and asp.net mvcDifference between asp.net web forms and asp.net mvc
Difference between asp.net web forms and asp.net mvcUmar Ali
 
ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1Umar Ali
 
Link checkers 1
Link checkers 1Link checkers 1
Link checkers 1Umar Ali
 
Affiliate Networks Sites-1
Affiliate Networks Sites-1Affiliate Networks Sites-1
Affiliate Networks Sites-1Umar Ali
 
Technical Video Training Sites- 1
Technical Video Training Sites- 1Technical Video Training Sites- 1
Technical Video Training Sites- 1Umar Ali
 
US News Sites- 1
US News Sites- 1 US News Sites- 1
US News Sites- 1 Umar Ali
 
How to create user friendly file hosting link sites
How to create user friendly file hosting link sitesHow to create user friendly file hosting link sites
How to create user friendly file hosting link sitesUmar Ali
 
Weak hadiths in tamil
Weak hadiths in tamilWeak hadiths in tamil
Weak hadiths in tamilUmar Ali
 
Bulughul Maram in tamil
Bulughul Maram in tamilBulughul Maram in tamil
Bulughul Maram in tamilUmar Ali
 
Asp.net website usage and job trends
Asp.net website usage and job trendsAsp.net website usage and job trends
Asp.net website usage and job trendsUmar Ali
 
Indian news sites- 1
Indian news sites- 1 Indian news sites- 1
Indian news sites- 1 Umar Ali
 
Photo sharing sites- 1
Photo sharing sites- 1 Photo sharing sites- 1
Photo sharing sites- 1 Umar Ali
 
File hosting search engines
File hosting search enginesFile hosting search engines
File hosting search enginesUmar Ali
 
Ajax difference faqs compiled- 1
Ajax difference  faqs compiled- 1Ajax difference  faqs compiled- 1
Ajax difference faqs compiled- 1Umar Ali
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1Umar Ali
 
Dotnet differences compiled -1
Dotnet differences compiled -1Dotnet differences compiled -1
Dotnet differences compiled -1Umar Ali
 

More from Umar Ali (20)

Difference between wcf and asp.net web api
Difference between wcf and asp.net web apiDifference between wcf and asp.net web api
Difference between wcf and asp.net web api
 
Difference between ActionResult() and ViewResult()
Difference between ActionResult() and ViewResult()Difference between ActionResult() and ViewResult()
Difference between ActionResult() and ViewResult()
 
Difference between asp.net mvc 3 and asp.net mvc 4
Difference between asp.net mvc 3 and asp.net mvc 4Difference between asp.net mvc 3 and asp.net mvc 4
Difference between asp.net mvc 3 and asp.net mvc 4
 
Difference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvcDifference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvc
 
Difference between asp.net web forms and asp.net mvc
Difference between asp.net web forms and asp.net mvcDifference between asp.net web forms and asp.net mvc
Difference between asp.net web forms and asp.net mvc
 
ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1ASP.NET MVC difference between questions list 1
ASP.NET MVC difference between questions list 1
 
Link checkers 1
Link checkers 1Link checkers 1
Link checkers 1
 
Affiliate Networks Sites-1
Affiliate Networks Sites-1Affiliate Networks Sites-1
Affiliate Networks Sites-1
 
Technical Video Training Sites- 1
Technical Video Training Sites- 1Technical Video Training Sites- 1
Technical Video Training Sites- 1
 
US News Sites- 1
US News Sites- 1 US News Sites- 1
US News Sites- 1
 
How to create user friendly file hosting link sites
How to create user friendly file hosting link sitesHow to create user friendly file hosting link sites
How to create user friendly file hosting link sites
 
Weak hadiths in tamil
Weak hadiths in tamilWeak hadiths in tamil
Weak hadiths in tamil
 
Bulughul Maram in tamil
Bulughul Maram in tamilBulughul Maram in tamil
Bulughul Maram in tamil
 
Asp.net website usage and job trends
Asp.net website usage and job trendsAsp.net website usage and job trends
Asp.net website usage and job trends
 
Indian news sites- 1
Indian news sites- 1 Indian news sites- 1
Indian news sites- 1
 
Photo sharing sites- 1
Photo sharing sites- 1 Photo sharing sites- 1
Photo sharing sites- 1
 
File hosting search engines
File hosting search enginesFile hosting search engines
File hosting search engines
 
Ajax difference faqs compiled- 1
Ajax difference  faqs compiled- 1Ajax difference  faqs compiled- 1
Ajax difference faqs compiled- 1
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1
 
Dotnet differences compiled -1
Dotnet differences compiled -1Dotnet differences compiled -1
Dotnet differences compiled -1
 

Recently uploaded

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 

Recently uploaded (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

ADO.NET difference faqs- 3

  • 1. 1.Difference between ExecuteNonQuery() and ExecuteScalar() methods in ADO.NET S.No ExecuteNonQuery() ExecuteScalar() 1 It will work with Action Queries It will work with Non-Action Queries only that contain aggregate functions. (Create,Alter,Drop,Insert,Update, Delete). 2 It returns the count of rows It returns the first row and first column effected by the Query. value of the query result. 3 Return type is int Return type is object. 4 Return value is optional and can Return value is compulsory and should be assigned to an integer variable. be assigned to a variable of required type. Example-1 for ExecuteNonQuery Method -Insert: SqlCommand cmd = new SqlCommand("Insert Into SampleTable Values('1','2')",con); //con is the connection object con.Open(); cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed Example-2 for ExecuteNonQuery Method - Update: public void UpdateEmployeeEmail() { SqlConnection conn = new SqlConnection(connString)) String sqlQuery = "UPDATE Employee SET empemail='umar.ali@xyz.com' WHERE empid=5; SqlCommand cmd = new SqlCommand(sqlQuery, conn); try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); } return count; }
  • 2. Example-1 for ExecuteScalar Method: This returns only one value that is first column value of the first row in the executed query 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; } Example-2 for ExecuteScalar Method: This returns one value only, no recordsets. cmd.CommandText = "Select Name, DOB, from Emp where ID=1"; Dim strName As string = cmd.ExecuteScalar.ToString 2.Difference between ExecuteNonQuery() and ExecuteReader() methods in ADO.NET S.No ExecuteNonQuery() ExecuteReader() 1 It will work with Action Queries It will work with Action and Non- only Action Queries (Select) (Create,Alter,Drop,Insert,Update, Delete). 2 It returns the count of rows It returns the collection of rows effected by the Query. selected by the Query. 3 Return type is int Return type is DataReader. 4 Return value is optional and can Return value is compulsory and should
  • 3. be assigned to an integer variable. be assigned to an another object DataReader. Example-1 for ExecuteNonQuery Method -Insert: SqlCommand cmd = new SqlCommand("Insert Into SampleTable Values('1','2')",con); //con is the connection object con.Open(); cmd.ExecuteNonQuery(); //The SQL Insert Statement gets executed Example-2 for ExecuteNonQuery Method - Update: public void UpdateEmployeeEmail() { SqlConnection conn = new SqlConnection(connString)) String sqlQuery = "UPDATE Employee SET empemail='umar.ali@xyz.com' WHERE empid=5; SqlCommand cmd = new SqlCommand(sqlQuery, conn); try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); } return count; } Example for ExecuteReader Method: Here, ExecuteReader is used to get set of records by specified query, namely, "select * from emp" SqlConnection con = new SqlConnection(constr); //constructor can be connection of string. SqlCommand cmd = new SqlCommand ("select * from emp", con); con.Open(); SqlDataReader dr = cmd. ExecuteReader (CommandBehavior. CloseConnection); //Implicitly closes the connection because CommandBehavior. CloseConnection was specified. while(dr.Read()) { Console.WriteLine (dr.GetString(0)); } dr.Close();
  • 4. And, further updates on difference between questions and answers, please visit my blog @ http://onlydifferencefaqs.blogspot.in/