从ORACLE返回DataTable

时间:2015-06-18 12:19:45

标签: oracle datatable

我试图将数据从Oracle获取到Datatable。我的想法是创建一个函数来完成所有连接人员,然后从代码的其他部分调用它。

像:

 dt = New DataTable
 dt = Oracle2table(sql.ToString)

然后,我创建了函数:

Function Oracle2table(ByVal sql As String) As DataTable

    Oracle2table = Nothing

    Try
        conn = New OleDb.OleDbConnection(connString)

        conn.Open()

        cmd = New OleDbCommand(sql, conn)

        adaptador = New OleDbDataAdapter
        adaptador.SelectCommand = cmd

        adaptador.Fill(Oracle2table)

        conn.Dispose()

    Catch ex As Exception
        MessageBox.Show("Error al cargar la tabla. ERROR = " + ex.ToString)

    Finally

        Oracle2table = Nothing

    End Try

End Function

此代码的问题是初始化变量( Oracle2table = nothing ),因此我没有收到函数错误。

1 个答案:

答案 0 :(得分:0)

我不是VB专家,但是这段代码工作得很好,所以它对你有用:

Dim dt = Oracle2table("select * from dual")
Console.WriteLine(dt.Rows(0)(0))

功能(为简单起见,我删除了异常处理):

Function Oracle2table(ByVal sql As String) As DataTable
    Dim conn = New OleDbConnection(connString)

    Oracle2table = New DataTable
    conn = New OleDb.OleDbConnection(connString)
    conn.Open()
    Dim cmd = New OleDbCommand(sql, conn)

    Dim adaptador = New OleDbDataAdapter
    adaptador.SelectCommand = cmd
    adaptador.Fill(Oracle2table)
    conn.Dispose()
End Function