Mega Code Archive

 
Categories / C# / ADO Database
 

Get result data from SqlDataReader by type

using System; using System.Data; using System.Data.SqlClient;    class TypedMethods    {       static void Main(string[] args)       {          string connString = "server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";          string sql = @"select * from employee";          SqlConnection conn = new SqlConnection(connString);          try {             conn.Open();             SqlCommand cmd = new SqlCommand(sql, conn);             SqlDataReader reader = cmd.ExecuteReader();             while(reader.Read()) {                Console.WriteLine( "{0}\t {1}\t\t {2}\t {3}",                    // nvarchar                   reader.GetString(0).PadRight(30),                   // money                   reader.GetDecimal(1),                   // smallint                   reader.GetInt16(2),                   // bit                   reader.GetBoolean(3));             }             reader.Close();          } catch(Exception e) {             Console.WriteLine("Error Occurred: " + e);          } finally {             conn.Close();          }       }    }