VB.NETでOracleデータベースを検索するサンプルです。
サンプル
このようなテーブルを想定します。
CD | NAME | |
---|---|---|
1 | 100 | 佐藤 |
2 | 200 | 鈴木 |
3 | 300 | 田中 |
4 | 400 | 伊藤 |
5 | 500 | 高橋 |
例)OracleデータベースをSELECTするサンプル
Imports Oracle.DataAccess.Client
Imports System.Configuration
Private Sub SelectSample()
'DB定義
Dim c As OracleConnection = New OracleConnection
Dim oc As OracleCommand = New OracleCommand()
Dim odr As OracleDataReader = Nothing
Try
'検索オブジェクトの生成
c.ConnectionString = ConfigurationManager.ConnectionStrings("oracleTest").ConnectionString
oc.Connection = c
oc.CommandType = CommandType.Text
oc.BindByName = True
'SQLとパラメータの生成
oc.CommandText = "SELECT * FROM test_table WHERE cd = :cd "
oc.Parameters.Add("cd", OracleDbType.Varchar2, 3, "400", ParameterDirection.Input)
'実行
c.Open()
odr = oc.ExecuteReader()
'値取得
Do While odr.Read()
Dim nm As String = odr.Item("name").ToString
Debug.Write(nm)
Loop
Catch ex As Exception
Throw ex
Finally
'後処理
If odr IsNot Nothing Then odr.Close()
c.Close()
oc = Nothing
End Try
End Sub
結果
伊藤
備考
- ※Oracleコネクションの設定については以下記事をご覧ください。
⇒ [ASP.NET] Oracleコネクションを取得する