TOP > ADO.NET2.0 - ODP.NET接続型

接続型と非接続型

データ参照時にDBに接続していなければならない「接続型」と
ADO.NETのDataTableオブジェクトやDataSetオブジェクトにデータを取得してから使い、
データ参照時には接続している必要のない「非接続型」がある。


ここでは、接続型でのデータ取得についてメモします。

 

odp.netの参照設定

Oracle DataAccessへの参照を追加してください。

ODP.NET参照設定

 

接続型

DataReaderを使って1レコード読み込んだ時DBから1レコード取得する為Readメソッドを実行している間は、Oracleと接続が維持されている必要がある。

 

データを読むサンプル -- EMP表の内容を取得し表示する。

サンプル EMP表の内容を取得し表示する。

サンプルプログラム

取得ボタンを押したあと

ソース

Imports Ora = Oracle.DataAccess.Client

Private Sub cnOpenClose(ByVal isOpen As Boolean)
	Try
    	If IsNothing(oraCn) Then
        	oraCn = New Ora.OracleConnection( _
            "data source=orcl;User id=scott;Password=tiger;")
        End If
        If isOpen Then
        	If Not oraCn.State = ConnectionState.Open Then
            	oraCn.Open()
            End If
        Else
            If oraCn.State = ConnectionState.Open Then
        	    oraCn.Close()
            End If
        End If
    Catch ex As Ora.OracleException
    	Throw New ApplicationException(ex.Message)

    Catch ex As Exception
        Throw New ApplicationException(ex.Message)

    End Try
End Sub

Private Sub getData_EMP()
    Dim oraCmd As Ora.OracleCommand = Nothing
    Dim oraRd As Ora.OracleDataReader = Nothing
    Try
       'DB接続
	cnOpenClose(True)

         'Command
        oraCmd = New Ora.OracleCommand( _
                "select ENAME,JOB from EMP where EMPNO = " & _
				TextBox1.Text, oraCn)

         ’Reader
		oraRd = oraCmd.ExecuteReader
        If oraRd.Read Then
            TextBox2.Text = oraRd.Item("ENAME").ToString.TrimEnd
            TextBox3.Text = oraRd.Item("JOB").ToString.TrimEnd
        End If
		 '必ずClose!!!
        oraRd.Close()

     Catch ex As Exception
        Msg = ex.ToString
        Msgtitle = "レコード取得エラー"
        MessageBox.Show(Msg, Msgtitle, MessageBoxButtons.OK, _
		MessageBoxIcon.Error)
     Finally
        If Not IsNothing(oraRd) Then
            If Not oraRd.IsClosed Then
                oraRd.Close()
            End If
            oraRd.Dispose()
        End If
        If Not IsNothing(oraCmd) Then
            oraCmd.Dispose()
        End If

        'DB切断
        cnOpenClose(False)
    End Try
End Sub

Private Sub Button1_Click( _
		ByVal sender As System.Object, ByVal e As System.EventArgs) _
		Handles Button1.Click
    getData_EMP()

End Sub

接続を開きます

ConnectionStringプロパティに接続文字列をセットします。
Openメソッドを実行します。

データを選択

OracleCommandオブジェクトに選択条件(SQL)を設定して、ExecuteReaderメソッドを実行。
ExecuteReaderメソッドの実行により、Oracle上に選択条件を満たすレコードが確保され、レコードを読み出す為のカーソル情報をメソッドの戻り値として返します。
この返された値を受け取るのがOracleDataReader。

SELECT文とOracleConnectionオブジェクトを設定して、OracleCommandオブジェクトを生成。

OracleDataReaderのReadメソッドで、Oracleカーソル位置にある1レコードをOracleDataReaderのItemコレクションに転記。
(1回のReadメソッドで読むレコード数はDataReaderのFetchSizeとレコード長で決まる)

itemオブジェクトに入った値をTextBoxのTextプロパティにセット。

OracleDataReaderは使い終わったら必ずCloseする。

Oracleと切断

Oracleデータベースと切断します。

このような手順でデータを取得します。
DataReaderは一般的に高速であるとされますが、先頭からしか読めないなど注意事項があります。
あと、接続されている状態で処理する事と、DataReaderをCloseする事をお忘れなく!