ADO - SQL Server - Display Record
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Data Source=(local);Initial Catalog=YourDatabaseName;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
// Connection opened successfully
Console.WriteLine("Connected to the database.");
// Retrieve records
string selectQuery = "SELECT * FROM YourTableName";
SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
SqlDataReader reader = selectCommand.ExecuteReader();
// Process the query results
while (reader.Read())
{
int id = (int)reader["Id"];
string name = (string)reader["Name"];
Console.WriteLine($"Id: {id}, Name: {name}");
}
reader.Close();
}
catch (Exception ex)
{
// Handle any errors
Console.WriteLine("Error: " + ex.Message);
}
}
}
}
In the above code, make sure to replace "YourDatabaseName" with the actual name of the database you want to connect to, and "YourTableName" with the name of the table you want to retrieve records from.
Here's an explanation of the code:
- We start by defining the connection string, which includes the necessary details to connect to the SQL Server database. Update the "Data Source" to your server name or IP address, and "Initial Catalog" to your database name.
- Inside the using block, we create a new SqlConnection object and pass the connection string as the constructor parameter. The using statement ensures that the connection is properly closed and disposed of when we're done with it.
- We attempt to open the connection using the Open method. If the connection is successful, we print a message indicating that the connection has been established.
- We define the SQL query to retrieve records from the table in the selectQuery variable. Replace "YourTableName" with the name of your table.
- We create a new SqlCommand object with the selectQuery and the connection as parameters.
- We execute the query using the ExecuteReader method of the SqlCommand object. This method is used for executing queries that return a result set. It returns a SqlDataReader object that we can use to iterate over the query results.
- Inside the while loop, we use the Read method of the SqlDataReader object to move to the next record in the result set. We then retrieve the values of the "Id" and "Name" columns using reader["ColumnName"], casting them to the appropriate data types.
- We print the retrieved values to the console. You can modify this part to process the retrieved data as per your application's requirements.
- After iterating over all the records, we close the SqlDataReader.
- If any errors occur during the process, they are caught in the catch block, and an error message is displayed.