We have 4 types of Exceute methods, through which we can excecute the quries angainst Database.
1). ExecuteNonQuery(()
2). ExecuteReader()
3). ExecuteScalar()
4). ExceuteXmlReader()
1). ExecuteNonQuery(()
Explanation: Executes a command but does not return any value or output
usage conditions: UPDATE, INSERT, DELETE statements
using System;
using System.Data;
public class exampleone
{
publis static void main(string[] args)
{
string source="server=(local);" +
"integrated security=SSPI;"+
"databs=dbNAME";
string select="UPDATE table set name='newname' where name='raj'";
SqlConnection conn = new SqlConection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select,conn);
int rowsreturn = cmd.ExecuteNonQuery();
Response.Write(rowsreturn);
conn.Close();
}
}
2). ExecuteReader()
Explanation: Executes a command and returns a typed data reader object.
usage conditions: Display Data
using System;
using System.Data;
public class exampletwo
{
publis static void main(string[] args)
{
string source="server=(local);" +
"integrated security=SSPI;"+
"databs=dbNAME";
string select="SELECT * from Tablename";
SqlConnection conn = new SqlConection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select,conn);
SqlDataReader reader = cmd.ExecuteReader();
while(dr.Read())
{
Response.write(dr[0].ToString());
}
}
}
3). ExecuteScalar()
Explanation: Executes a command and returns a single result.
usage conditions: count of records, time etc.
using System;
using System.Data;
public class exampletwo
{
publis static void main(string[] args)
{
string source="server=(local);" +
"integrated security=SSPI;"+
"databs=dbNAME";
string select="SELECT count(*) from Tablename";
SqlConnection conn = new SqlConection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select,conn);
object o = cmd.ExecuteScalar();
Response.write(o);
}
}
4). ExecuteXmlReader()
Explanation: Executes a command and returns a XmlReader Object.
using System;
using System.Data;
using System.Xml
public class exampletwo
{
publis static void main(string[] args)
{
string source="server=(local);" +
"integrated security=SSPI;"+
"databs=dbNAME";
string select="SELECT name,address from Tablename FOR XML AUTO ";
SqlConnection conn = new SqlConection(source);
conn.Open();
SqlCommand cmd = new SqlCommand(select,conn);
XmlReader xr = cmd.ExecuteXmlReader();
xr.read();
do
{
s = xr.ReadOuterXml();
if(s!=="")
Response.Write(s);
} while (s!="");
conn.Close();
}
}
About the author:
PlanetSourceCode.in is a place for all developer providing free source codes, articles, complete projects,complete application in PHP, C/C++, Javascript, Visual Basic, Cobol, Pascal, ASP/VBScript, AJAX, SQL, Perl, Python, Ruby, Mobile Development- Add new comment
- 15 views