// Define connection string for SQL Server
string connectionString = “Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;”;
// Define SQL query to retrieve data
string sqlQuery = “SELECT * FROM myTable;”;
// Create a new SqlConnection object using the connection string
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Open the connection to the database
connection.Open();
// Create a new SqlCommand object using the SQL query and SqlConnection
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// Execute the SQL query and retrieve data using a SqlDataReader
using (SqlDataReader reader = command.ExecuteReader())
{
// Iterate through each row of data returned by the query
while (reader.Read())
{
// Access the data in each column of the current row using the column index or name
int id = reader.GetInt32(0);
string name = reader.GetString(1);
DateTime dateOfBirth = reader.GetDateTime(2);
// Do something with the retrieved data, such as displaying it in a web page
}
}
}
}

Ankit Srivastava is an IT trainer, technology educator, and digital skills mentor with expertise in programming, data analytics, AI, and software development. He has successfully trained thousands of learners, with more than 10,000 student enrollments on Udemy. His practical teaching approach empowers students and professionals to build in-demand technical skills. Colorstech channel where Ankit posts video tutorials has more than 8000 Subscribers.

