Monday, February 15, 2010

How to connect with database, execute command and read data in ADO.NET?

Basically we need three Classes in ADO.NET; these are SqlConnection, SqlCommand, SqlDataReader.
Following are the parameter which is needed for SQLConnection
1)    Server name (for example xyz.com)
2)    User ID (the username for the database)
3)    Password (the password for the database)
4)    Name of database (only the database name – not a table name)
Example: -
private SqlConnection hookup;
------------
hookUp = new SqlConnection(“Server=xyz.com;uid=uname;pwd=pass;database=databaseName”);

SqlCommand: The Command to Query
The SqlCommand is a class to gather up our SQL commands and send them to the server via the connection we have established using SqlConnection. The general format is

SqlCommand(“SQL query”, myConnection)

SqlDataReader: Shows What You Found
This is a command which read the results of a table query and return the database contents in such a way that they can be passed to variables and sent to ASP.NET web controls. The SqlDataReader instance uses the SqlCommand instance to launch the reader that returns array elements of the query data from the table. The element values can then be passed to variables and on to web controls or we can pass the element values directly to the controls. It has the following format:

private SqlDataReader reader;
---
reader = sqlCmd.ExecuteReader();
while (reader.Read())
{
var1 = Convert.ToString(reader[“Field1”]);
var2 = Convert.ToString(reader[“Field2”]);
WebControl.Text += var1 + var2 + “<br/>”;
}
Reader.Close();

No comments:

Post a Comment