Tuesday, May 5, 2009

Explain DataView

A DataView enables us to create different views of the data stored in a DataTable, a capability that is often used in data-binding applications. Using a DataView, we can expose the data in a table with different sort orders, and we can filter the data by row state or based on a filter expression.

It provides a means to filter and sort data within a data table.

Example:
DataView myDataView = new DataView(myDataSet.Tables["Customers"]);

// Sort the view based on the FirstName column
myDataView.Sort = "CustomerID";

// Filter the dataview to only show customers with the CustomerID of XYZ
myDataView.RowFilter = "CustomerID=XYZ";

Friday, May 1, 2009

Difference between ExecuteNonQuery, ExecuteScaler, ExecuteReader

Difference Angle

ExecuteNonQuery

ExecuteScaler

ExecuteReader

About

After Executing Sql statement Returns number of rows affected

Returns Single value, Executes first column first row only

Send the Command text to connection and builds a SqlDataReader.

When we use

ExecuteNonQuery is used to perform Catalog operation like Creating table in database or Changing of data in tables (without using Dataset) by using Insert, Update, Delete, create

Selecting only single fields like count field

When we manipulating with DataReader it used, Sending SQL Select statements to a database, Invoking Stored Procedures

Example

Example:
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
This method returns no data at all. It is used majorly with Inserts and Updates of tables. It is used for execution of DML commands.

Example : select count(*) from emp

ExecuteScalar is used to get aggregate value. ExecuteScalar will return only one value that is first column value of the first row in the executed query.

Example 2:
cmd.CommandText = "Select Name, DOB, from Emp where ID=1";
Dim strName As string = cmd.ExecuteScalar.ToString
This returns one value only, no recordsets.

Example:
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);

while(dr.Read())
{
Console.WriteLine (dr.GetString(0));
}
dr.Close();

//Implicitly closes the connection because CommandBehavior. CloseConnection was specified.
ExecuteReader is used to get set records by specified query