// 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
}
}
}
}