Use the GetOrdinal() method of a DataReader object to get the numeric positions of a column : SqlCommand : Database C# Source Code


Custom Search

C# Source Code » Database » SqlCommand »

 

Use the GetOrdinal() method of a DataReader object to get the numeric positions of a column








    

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

class UsingColumnOrdinals
{
  public static void Main()
  {
    SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");

    SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

    mySqlCommand.CommandText = "SELECT TOP 5 ID, FirstName, LastName FROM employee " +
      "ORDER BY ID";

    mySqlConnection.Open();

    SqlDataReader productsSqlDataReader = mySqlCommand.ExecuteReader();

    int idPos = productsSqlDataReader.GetOrdinal("ID");
    int firstNamePos = productsSqlDataReader.GetOrdinal("LastName");
    int lastNamePos = productsSqlDataReader.GetOrdinal("FirstName");

    while (productsSqlDataReader.Read())
    {
      Console.WriteLine("ID = " + productsSqlDataReader[idPos]);
      Console.WriteLine("FirstName = " + productsSqlDataReader[firstNamePos]);
      Console.WriteLine("LastName = " + productsSqlDataReader[lastNamePos]);
    }

    productsSqlDataReader.Close();
    mySqlConnection.Close();
  }
}



           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Database
» SqlCommand