■■■

2016年4月6日水曜日

【DB】Oracleへ接続してデータ操作を行う方法(検索、更新、削除)

ODP.NETのインストール

オラクルサイト:「Oracle Technology Network」(略称はOTN)から「ODP.NET」をダウンロードしてインストールします。


VB.NET

Imports System.Data.Common

Private Sub DbConnect()

' ProviderFactoryの設定
Dim factory As DbProviderFactory = DbProviderFactories.GetFactory("Oracle.DataAccess.Client")
Dim csbuilder As DbConnectionStringBuilder = factory.CreateConnectionStringBuilder()
csbuilder("Data Source") = "ORCL10GR2"
csbuilder("User ID") = "Scott"
csbuilder("Password") = "Tiger"

' データベース接続
Dim conn As DbConnection = factory.CreateConnection()
conn.ConnectionString = csbuilder.ConnectionString
conn.Open()

' データアクセス処理
Dim cmd As DbCommand = factory.CreateCommand()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * FROM emp"
Dim reader As DbDataReader = cmd.ExecuteReader()
' 処理の実行
While reader.Read()
End While

' Close
conn.Close()
conn.Dispose()
End Sub


C#

using System.Data.Common;

private void DbConnect(){

  // ProviderFactoryの設定
  DbProviderFactory factory
    = DbProviderFactories.GetFactory("Oracle.DataAccess.Client");
  DbConnectionStringBuilder csbuilder
    = factory.CreateConnectionStringBuilder();
  csbuilder("Data Source") = "ORCL10GR2";
  csbuilder("User ID") = "Scott";
  csbuilder("Password") = "Tiger";

  // データベース接続
  DbConnection conn = factory.CreateConnection();
  conn.ConnectionString = csbuilder.ConnectionString;
  conn.Open();

  // データアクセス処理
  DbCommand cmd =  factory.CreateCommand();
  cmd.Connection = conn;
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = "SELECT * FROM emp";
  DbDataReader reader = cmd.ExecuteReader();
  while(reader.Read()){
    // 処理の実行
  }

  // Close
  conn.Close();
  conn.Dispose();
}








■■■