Friday, 6 December 2013

READING AND WRITING DATA-----(ExecuteScalar Method)

ExecuteScalar Method
Queries are often expected to return a single row with a single column. In these situations,
the results can be treated as a single return value. For example, the following SQL returns a
result that consists of a single row with a single column.

Sample SQL Statement





SELECT COUNT(*) FROM Products


If we use the ExecuteScalar method, the .NET Framework run time will not incur the overhead
to produce objects that read the result stream, which means less resource usage and
better performance. The following code shows how to use the ExecuteScalar method to easily
retrieve the number of rows in the Sales table directly into a variable called count.

C# Code:


var nw = ConfigurationManager.ConnectionStrings["nw"];
var connection = new SqlConnection();
connection.ConnectionString = nw.ConnectionString;
var cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT COUNT(*) FROM Products";
connection.Open();
int count = (int)cmd.ExecuteScalar();
connection.Close();
MessageBox.Show(count.ToString());

No comments:

Post a Comment