到整型的显式转换显示如下:
Label1.Text = CStr(dr.Item("deptno")) ' VB.net integer to string cast
  在隐式转换上,C# 的容错能力不如 VB.net。 您必须自己执行显式转换:
string deptno = dr.GetInt16("deptno").ToString(); // C#
  您可以显式地转换标量值以及数组。

  关闭并清除

  可以调用连接对象的 Close 方法或 Dispose 方法来关闭到数据库的连接。 Dispose 方法调用 Close 方法。

conn.Close() ' VB.NET
conn.Dispose() ' VB.NET
conn.Close(); // C#
conn.Dispose(); // C#
  作为可选项,C# 提供了一种在连接超出范围时自动清除连接的特殊语法。 使用 using 关键字可启用这一特性。
using (OracleConnection conn = new OracleConnection(oradb))
{
conn.Open();
OracleCommand cmd = new OracleCommand();
    cmd.Connection = conn;
    cmd.CommandText = "select dname from dept where deptno = 10";
cmd.CommandType = CommandType.Text;
 
 OracleDataReader dr = cmd.ExecuteReader();
    dr.Read();
    label1.Text = dr.GetString(0);
}

  您可以试验在上机操作 1(从数据库中检索数据)和上机操作 2(增加交互性)中学到的一些概念。

错误处理

  Try-Catch-Finally 结构的错误处理是 .net 语言的一部分。 下面是使用 Try-Catch-Finally 语法的一个相对最小的例子:

Dim conn As New OracleConnection(oradb) ' VB.NET
Try
    conn.Open()
    Dim cmd As New OracleCommand
    cmd.Connection = conn
    cmd.CommandText = "select dname from dept where deptno = " + TextBox1.Text
cmd.CommandType = CommandType.Text
    If dr.Read() Then
        Label1.Text = dr.Item("dname") ' or use dr.Item(0)
    End If
Catch ex As Exception ' catches any error
    MessageBox.Show(ex.Message.ToString())
Finally
    conn.Dispose()
End Try
OracleConnection conn = new OracleConnection(oradb); // C#
try
{
conn.Open();
OracleCommand cmd = new OracleCommand();
    cmd.Connection = conn;
    cmd.CommandText = "select dname from dept where deptno = " + textBox1.Text;
cmd.CommandType = CommandType.Text;
    if (dr.Read()) // C#
    {
        label1.Text = dr.GetString(0);
    }
}
catch (Exception ex) // catches any error
{
    MessageBox.Show(ex.Message.ToString());
}
finally
{
    conn.Dispose();
}

  虽然这种方法将适当地捕获尝试从数据库中获取数据时发生的任何错误,但这种方法对用户却不友好。 例如,看看下面这条在数据库不可用时显示的消息。

图 6: 捕获到一个 ORA-12545 错误,并向用户显示。