how to execute a SELECT statement using a SqlCommand object : Select « Database ADO.net « C# / C Sharp






how to execute a SELECT statement using a SqlCommand object

 


using System;
using System.Data;
using System.Data.SqlClient;

class ExecuteSelect {
    public static void Main() {
        SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
        SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
        mySqlCommand.CommandText =
          "SELECT TOP 5 CustomerID, CompanyName, ContactName, Address " +
          "FROM Customers " +
          "ORDER BY CustomerID";

        mySqlConnection.Open();
        SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
        while (mySqlDataReader.Read()) {
            Console.WriteLine("mySqlDataReader[\" CustomerID\"] = " + mySqlDataReader["CustomerID"]);
            Console.WriteLine("mySqlDataReader[\" CompanyName\"] = " + mySqlDataReader["CompanyName"]);
            Console.WriteLine("mySqlDataReader[\" ContactName\"] = " + mySqlDataReader["ContactName"]);
            Console.WriteLine("mySqlDataReader[\" Address\"] = " + mySqlDataReader["Address"]);
        }
        mySqlDataReader.Close();
        mySqlConnection.Close();
    }
}

 








Related examples in the same category

1.Populate a DataSet object with a range of rows from a SELECT statement
2.How to control the command behavior to return a single row