How to Execute SQL Statements: ADO.NET

We have learnt about ADO.NET object model. In that article we have created a SQL connection, open that connection and close that connection. To execute the SQL statements, we have to write them in between the open and close method of the above connection.

So to execute the SQL statement we have to, first create the connection, open that, write some code which will be executed and at the last execute it with ExecuteReader() method of SQLCommand class.

SqlCommand class is used to specify the Sql statement to be executed and the connection that need to be used. It can also be used to execute stored procedures. Following code will used to execute Sql statement in a command object:

SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source=(LocalDb)\v11.0; Initial Catalog=StockDb; Integrated Security=True";
SqlCommand command = new SqlCommand("select * from Groups", connection);
SqlDataReader dr = command.ExecuteReader();

In the above code, when SqlCommand object will create, an object of SqlDataReader have been also created. And it is initialized with the function ExecuteReader(). Now all the data can be accessed one by one through dr object, one by one.

When we check the dataReader object through the breakpoint then there are some rows, as shown in following image:

Execute SQL Statement in ADO.NET

See also: Parameterized Sql Queries


Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites