C# Example: Connecting to a database, executing a query, and retrieving and displaying the results - Biz Tech

C# Example: Connecting to a database, executing a query, and retrieving and displaying the results

Listen
using System;
using System.Data.SqlClient;

class Program
{
    static void Main(string[] args)
    {
        string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            string sql = "SELECT * FROM Customers";

            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    Console.WriteLine(reader["CustomerName"] + " - " + reader["ContactName"]);
                }

                reader.Close();
            }

            connection.Close();
        }
    }
}
 

This example connects to a SQL Server database using a connection string, executes a SELECT query to retrieve data from the Customers table, iterates over the result set using a while loop, and outputs the customer names and contact names to the console. The following steps are performed:

  1. Define a connection string variable connectionString with the appropriate values for the server address, database name, username, and password.
  2. Use the SqlConnection class to create a new connection object and open the connection using the Open() method.
  3. Define a SQL query string sql that selects all columns from the Customers table.
  4. Use the SqlCommand class to create a new command object with the sql query string and the open connection.
  5. Use the ExecuteReader() method of the command object to execute the query and retrieve a SqlDataReader object.
  6. Use a while loop to iterate over the rows in the result set using the Read() method of the SqlDataReader object.
  7. Output the values of the CustomerName and ContactName columns from each row to the console using Console.WriteLine().
  8. Close the SqlDataReader object using the Close() method.
  9. Close the connection using the Close() method of the connection object.

Note that there are many other database-related concepts and operations you can perform, such as inserting, updating, and deleting records, as well as working with other database management systems such as MySQL, Oracle, and MongoDB. This example is just one possible multi-step process for working with databases.