Here’s a sample code in C# using the .NET framework to read data from a SQL Server database
using System; using System.Data; using System.Data.SqlClient; namespace SqlDatabaseReaderExample { class Program { static void Main(string[] args) { // Define the connection string for the SQL Server database string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=Username;Password=Password;"; // Define the SQL statement to select data from the SQL Server database string sql = "SELECT * FROM Customers"; // Create a new instance of the SqlConnection class using (SqlConnection connection = new SqlConnection(connectionString)) { // Open the connection to the SQL Server database connection.Open(); // Create a new instance of the SqlCommand class using (SqlCommand command = new SqlCommand(sql, connection)) { // Create a new instance of the SqlDataAdapter class using (SqlDataAdapter adapter = new SqlDataAdapter(command)) { // Create a new instance of the DataTable class DataTable table = new DataTable(); // Fill the DataTable with the results of the SQL statement adapter.Fill(table); // Print the results to the console foreach (DataRow row in table.Rows) { Console.WriteLine("{0}\t{1}\t{2}", row["FirstName"], row["LastName"], row["Email"]); } } } } Console.WriteLine("Data has been read from the SQL Server database."); Console.ReadLine(); } } }
In this example, the SqlConnection
class is used to create a new instance of the SQL connection to the SQL Server database. The Open
method of the SqlConnection
object is used to open the connection. The SqlCommand
class is used to create a new instance of the SQL command to select data from the SQL Server database. The SqlDataAdapter
class is used to create a new instance of the data adapter to fill a DataTable
object with the results of the SQL statement. The Fill
method of the SqlDataAdapter
object is used to fill the DataTable
with the results of the SQL statement. Finally, the results are printed to the console using a foreach
loop to iterate through the rows of the DataTable
.