Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 12.0.0 (中文) » UltraLite - .NET 编程 » 教程:构建 UltraLite.NET 应用程序

 

第 3 课:连接到数据库

以下过程向 UltraLite.NET 应用程序中添加一个控件,通过该控件与 UltraLite 数据库建立连接。

 ♦  向应用程序中添加 UltraLite 连接
  1. 双击窗体以打开源文件(Form1.csForm1.vb)。

  2. 添加用于导入 iAnywhere.Data.UltraLite 命名空间的代码。

    添加以下语句,作为该文件的第一行。

    //Visual C#
    using iAnywhere.Data.UltraLite;
    'Visual Basic
    Imports iAnywhere.Data.UltraLite
  3. 向窗体声明中添加全局变量。

    对于 Visual C#,在描述窗体组件的代码和第一个方法声明之间添加以下代码。

    //Visual C#
    private ULConnection Conn;
    private int[] ids;

    对于 Visual Basic,在 Form1 类的开始位置添加以下代码。

    'Visual Basic
    Dim Conn As ULConnection
    Dim ids() As Integer

    这些变量的用法如下:

    • ULConnection   Connection 对象是对数据库连接执行的所有操作的根对象。

    • ids   ids 数组用于保存执行查询后返回的 ID 列值。

      虽然 ListBox 控件本身允许访问顺序编号,但如果删除了行,这些编号就会与 ID 列值不同。因此,ID 列值必须单独存储。

  4. 双击窗体的空白处,创建一个 Form1_Load 方法。

    此方法执行以下任务:

    • 使用在 uLConnectionParms1 控件中设置的连接参数打开到数据库的连接。

    • 调用 RefreshListBox 方法(在本教程的稍后部分进行定义)。

    • 打印(显示)错误消息(如果出现错误)。对于 SQL Anywhere 错误,该代码还会打印错误代码。请参见错误消息

    对于 C#,请将以下代码添加到 Form1_Load 方法中。



    //Visual C#
    try {
        String ConnString = "dbf=\\Program Files\\CSApp\\CSApp.udb";
        Conn = new ULConnection( ConnString );
        Conn.Open();
        Conn.DatabaseID = 1;
        RefreshListBox();
    }
    catch ( System.Exception t ) {
        MessageBox.Show( "Exception: " + t.Message);
    }

    对于 Visual Basic,请将以下代码添加到 Form1_Load 方法中。



    'Visual Basic
    Try
        Dim ConnString as String = "dbf=\Program Files\VBApp\VBApp.udb"
        Conn = New ULConnection( ConnString )
        Conn.Open()
        Conn.DatabaseID = 1
        RefreshListBox()
    Catch
        MsgBox("Exception: " + err.Description)
    End Try
  5. 生成项目。

    从 [Build] 菜单中,选择 [Build Solution]。在此阶段,您可能会收到一条报告的错误;例如,在 C# 中:error CS0103: The name 'RefreshListBox' does not exist in the class or namespace 'CSApp.Form1',因为 RefreshListBox 还未进行声明。下一课将添加该函数。

    如果看到其它错误,则必须先纠正它们,然后再继续。检查常见的错误,比如 C# 中的大小写一致性问题。例如,UltraLiteULConnection 的大小写必须完全一致。在 Visual Basic 中,如第 3 课所述包括 Imports iAnywhere.Data.UltraLite 语句十分重要。