□C#でDBアクセス(Oracle)

1. 準備
 1)MS社サイトから無料でVisual Studio環境が提供されている。


 取得してお任せでインストールする。

 2) Oracleにアクセスする為に、ODT.netが必要、OTNのサインアップが必要だが以下から取得できるので、展開してインストールする



2. プロジェクト作成
 1) OracleのJavaでいうところのクラスライブラリにあたるものが、下の例の様なフォルダにインストールされるので、プロジェクトの参照にて設定する。

  X:\app\xxx\product\11.1.0\client_1\odp.net\bin\2.x

  →
  Oracle.DataAccess.dll

3. コーディング(↓サンプル)


using System;
using System.Data;
using Oracle.DataAccess.Client;

class Example
{
 OracleConnection con;

 void Connect()
 {
   con = new OracleConnection();
   con.ConnectionString = "User Id=pkg_test5;Password=pkg_test5;Data Source=ijidb";
   con.Open();
   Console.WriteLine("Connected to Oracle");
   Console.WriteLine(con.ServerVersion);
 }

 void execute()
 {
     string cmdQuery = "SELECT systimestamp(9) from dual";

     // Create the OracleCommand object
     OracleCommand cmd = new OracleCommand(cmdQuery);
     cmd.Connection = con;
     cmd.CommandType = CommandType.Text;
     try
     {
         // Execute command, create OracleDataReader object
         OracleDataReader reader = cmd.ExecuteReader();
         while (reader.Read())
         {
             // Output Employee Name and Number
             Console.WriteLine("Systimestampe(9): " + reader.GetDateTime(0)); 
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     finally
     {
         // Dispose OracleCommand object
         cmd.Dispose();

         // Close and Dispose OracleConnection object
         con.Close();
         con.Dispose();
     }
 }     
 void Close()
 {
   con.Close();
   con.Dispose();
 }

 static void Main()
 {
   Example example = new Example();
   example.Connect();
   example.execute();
     example.Close();
 }
}