Tuesday, January 24, 2023

How do I retrieve data from SQL Server using ASP .Net

In order to retrieve data from a SQL Server database in an ASP.NET application, you can use ADO.NET, which is a set of classes that provide data access services for the .NET Framework. The most commonly used classes for this purpose are the SqlConnection, SqlCommand, and SqlDataReader classes.

Here is an example of how you can use these classes to retrieve data from a SQL Server database and display it in an ASP.NET page:

Create a new SqlConnection object and set its connection string to the appropriate value for your SQL Server database.

Create a new SqlCommand object and set its CommandText property to the SQL query you want to execute.

Open the SqlConnection.

Execute the query by calling the ExecuteReader method of the SqlCommand object and store the result in a SqlDataReader object.

Iterate through the SqlDataReader object and retrieve the data you need.

Close the SqlConnection and SqlDataReader.

Here is an example of the above steps

Sample Code:


using (SqlConnection con = new SqlConnection(connectionString))
{
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
    {
        con.Open();
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // Retrieve data from the reader
                string name = reader["Name"].ToString();
                string city = reader["City"].ToString();
                // Do something with the data
            }
        }
        con.Close();
    }
}


It's also important to consider that this is just a simple example, and in production applications, you should handle exceptions, use parameters to avoid SQL injection, and dispose objects properly.

No comments: