Explain About SQLCommand Bilder


A Command object is used to execute scalar or non query commands to a database. You would set a command objects CommandText property to and sql statement that you want to run and then use it's ExecuteScalar or ExecuteNonQuery method to run it.

A CommandBuilder object is used to automatically create Update, Delete, and Insert SQL statements for you, based on a Select statament that you supply. You would declare a DataAdapter object, set it's SelectCommand.CommandText property to your Select SQL statement. Then when you declare a CommandBuilder object, you include the dataadapter in the CommandBuilder's constructor parameter and it will automatically create the other statements for you when you run a DataAdapter.






Example:



It is a class defined by System.Data.SqlClient namespace and is used to generate commands(insert,delete,update) that can be used

to reflect DataSet changes back to a sql server database

Update method of SqlDataAdapter uses the SqlCommandBuilder's commands
to reflect DataSet changes back to a sql server database.


example:

//save a record in a database using the Update method of SqlDataAdapter
using System.Data;
using System.Data.SqlClient;

class dd
{
static void Main()
{
SqlConnection cn=new SqlConnection("server=.;uid=sa;pwd=1234;database=employee");
SqlDataAdapter da=new SqlDataAdapter("select * from emp",cn);
DataTable dt=new DataTable();
da.Fill(dt);
//emp has 2 columns known as eno and ename.

//Initialize the SqlCommandBuilder.
SqlCommandBuilder cd=new SqlComandBuilder(da);

//create a DataRow
DataRow dr=dt.NewRow();
dr["eno"]=100;
dr["ename"]="king";
//the row is temporarily saved
dt.Rows.Add(dr);

//save the Row permanently
da.Update(dt);

}
} 

0 comments:

Post a Comment