Get row count from SqlCommand

 

use ExecuteScalar() to run a SELECT statement that returns a single value

   
 

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

class ExecuteScalar {
    public static void Main() {
        SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa");
        SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
        mySqlCommand.CommandText = "SELECT COUNT(*) FROM Products";
        mySqlConnection.Open();

        int returnValue = (int)mySqlCommand.ExecuteScalar();
        Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);

        mySqlConnection.Close();
    }
}

    


Get result data from SqlDataReader by type: decimal, string, int and boolean

   

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}	 {1}		 {2}	 {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();
         }
      }
   }



           
          


Result set info: field count and field type

   

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

   class ResultSetInfo{
      static void Main(string[] args) {
         string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";

         string sql = @"select FirstName, LastName from Employee";

         SqlConnection conn = new SqlConnection(connString);

         try {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader reader = cmd.ExecuteReader();
            Console.WriteLine("Column Name:	{0} {1}", reader.GetName(0).PadRight(25),reader.GetName(1));
            Console.WriteLine("Data Type:	{0} {1}", reader.GetDataTypeName(0).PadRight(25), reader.GetDataTypeName(1));
            Console.WriteLine("Number of columns in a row: {0}", reader.FieldCount);
            Console.WriteLine("'{0}' is at index {1} and its type is: {2}", 
               reader.GetName(0),reader.GetOrdinal("FirstName"),reader.GetFieldType(0));

            Console.WriteLine("'{0}' is at index {1} and its type is: {2}", 
               reader.GetName(1), reader.GetOrdinal("LastName"),reader.GetFieldType(1));
            reader.Close();
         }
         catch(Exception e)
         {
            Console.WriteLine("Error Occurred: " + e);
         }
         finally
         {
            conn.Close();
         }
      }  
   }



           
          


Result set info: column Name, column Type, type name

   

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

   class ResultSetInfo{
      static void Main(string[] args) {
         string connString = "server=(local)SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";

         string sql = @"select FirstName, LastName from Employee";

         SqlConnection conn = new SqlConnection(connString);

         try {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader reader = cmd.ExecuteReader();
            Console.WriteLine("Column Name:	{0} {1}", reader.GetName(0).PadRight(25),reader.GetName(1));
            Console.WriteLine("Data Type:	{0} {1}", reader.GetDataTypeName(0).PadRight(25), reader.GetDataTypeName(1));
            while(reader.Read()) {
               Console.WriteLine("		{0} {1}", 
                  reader.GetString(0).ToString().PadRight(25),
                  reader.GetString(1));
            }
            reader.Close();
         }
         catch(Exception e)
         {
            Console.WriteLine("Error Occurred: " + e);
         }
         finally
         {
            conn.Close();
         }
      }  
   }



           
          


Static Helper for executing SQL statements against Oracle Requires the ODP.NET provider

   
 
  
//---------------------------------------------------------------------
// File: OracleDatabaseHelperEx.cs
// 
// Summary: 
//
// Copyright (c) Hammersmith & Fulham Bridge Partnership. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------

using System;
using System.Data;
using System.Data.OracleClient;

namespace BizUnit.Extensions.Utilities
{
  /// <summary>
  /// Static Helper for executing SQL statements against Oracle
  /// Requires the ODP.NET provider
  /// </summary>
  public class OracleDatabaseHelperEx
  {
        #region constructor(s)
        /// <summary>
        /// Constructor for class, default constructor is private to prevent instances being
        /// created as the class only has static methods
        /// </summary>
        public OracleDatabaseHelperEx()
    {
    }
        #endregion

        #region Static Methods
        /// <summary>
        /// Excecutes the SQL statement against the database and returns a DataSet with the results
        /// </summary>
        /// <param name="connectionString">Database connection string</param>
        /// <param name="sqlCommand">SQL statement to execute</param>
        /// <returns>DataSet with the results of the executed command</returns>
        public DataSet ExecuteSqlCommand( string connectionString, string sqlCommand )
        {
            DataSet ds = new DataSet() ;
      try
      {
        using ( OracleConnection connection = new OracleConnection( connectionString ) )
        {
          OracleDataAdapter adapter = new OracleDataAdapter( sqlCommand, connection ) ;
          adapter.Fill( ds ) ;
        }   // connection
      }
      catch (Exception)
      {
        throw ;
      }
            return ds ;
        }

        /// <summary>
        /// Executes the SQL statement and returns the first column of the first row in the resultset returned by the query.
        /// </summary>
        /// <param name="connectionString">Database connection string</param>
        /// <param name="sqlCommand">SQL statement to execute</param>
        /// <returns>The contents of the first column of the first row in the resultset</returns>
        public int ExecuteScalar( string connectionString, string sqlCommand )
        {
            OracleConnection connection = null ;
            object col = 0 ;

            try 
            {
                connection = new OracleConnection( connectionString ) ;
                OracleCommand command = new OracleCommand( sqlCommand, connection ) ;
                command.Connection.Open() ;
                col = command.ExecuteScalar() ;
            }
            catch ( Exception )
            {
        throw;
            }
            finally 
            {
                connection.Close() ;
            }

            return Convert.ToInt32( col ) ;
        }

        /// <summary>
        /// Executes the SQL statement
        /// </summary>
        /// <param name="connectionString">Database connection string</param>
        /// <param name="sqlCommand">SQL statement to execute</param>
        public void ExecuteNonQuery( string connectionString, string sqlCommand )
        {
            OracleConnection connection = null ;

            try 
            {
                connection = new OracleConnection( connectionString ) ;
                OracleCommand command = new OracleCommand( sqlCommand, connection ) ;
                command.Connection.Open() ;
                command.ExecuteNonQuery() ;
            }
            catch ( Exception )
            {
        throw;
            }
            finally 
            {
                connection.Close() ;
            }
        }
        #endregion
  }
}

   
     


Connect to an Oracle server

   
 
using System;
using System.Data;
using System.Data.OracleClient;

class OracleConnect
{
   static void Main() 
   {
      string connString = @"server = myServer;uid = scott;password = tiger;";

      OracleConnection conn = new OracleConnection(connString);

      try 
      {
         conn.Open();
         Console.WriteLine("Connection opened.");

         Console.WriteLine("Connection Properties:");   
         Console.WriteLine("	Connection String: {0}", conn.ConnectionString);    
         Console.WriteLine("	ServerVersion: {0}", conn.ServerVersion);
         Console.WriteLine("	State: {0}", conn.State);
      } catch (OracleException e) {
         Console.WriteLine("Error: " + e);  
      } finally {
         conn.Close();
         Console.WriteLine("Connection closed.");
      }
   }
}