Connecting to a database

Before you can perform any operations on the data, your application must connect to the database. This section describes how to write code to connect to a SQL Anywhere database.

For more information, see SAConnectionStringBuilder class and ConnectionName property.

To connect to a SQL Anywhere database

  1. Allocate an SAConnection object.

    The following code creates an SAConnection object named conn:

    SAConnection conn = new SAConnection(connection-string)

    You can have more than one connection to a database from your application. Some applications use a single connection to a SQL Anywhere database, and keep the connection open all the time. To do this, you can declare a global variable for the connection:

    private SAConnection  _conn;

    For more information, see the sample code in samples-dir\SQLAnywhere\ADO.NET\TableViewer and Understanding the Table Viewer sample project.

  2. Specify the connection string used to connect to the database.

    For example:

    "Data Source=SQL Anywhere 11 Demo"

    For a complete list of connection parameters, see Connection parameters.

    Instead of supplying a connection string, you can prompt users for their user ID and password.

  3. Open a connection to the database.

    The following code attempts to connect to a database. It autostarts the database server if necessary.

    conn.Open();
  4. Catch connection errors.

    Your application should be designed to catch any errors that occur when attempting to connect to the database. The following code demonstrates how to catch an error and display its message:

    try {
        _conn = new SAConnection( txtConnectString.Text );
        _conn.Open();
      } catch( SAException ex ) {
        MessageBox.Show( ex.Errors[0].Source + " : "
         + ex.Errors[0].Message + " (" +
         ex.Errors[0].NativeError.ToString() + ")",
             "Failed to connect" );

    Alternately, you can use the ConnectionString property to set the connection string, rather than passing the connection string when the SAConnection object is created:

    SAConnection _conn;
        _conn = new SAConnection();
        _conn.ConnectionString =
         "Data Source=SQL Anywhere 11 Demo";
        _conn.Open();
  5. Close the connection to the database. Connections to the database stay open until they are explicitly closed using the conn.Close() method.

Visual Basic connection example

The following Visual Basic code opens a connection to the SQL Anywhere sample database:

Private Sub Button1_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) _
    Handles Button1.Click
    ' Declare the connection object
    Dim myConn As New _
      iAnywhere.Data.SQLAnywhere.SAConnection()
    myConn.ConnectionString = _
      "Data Source=SQL Anywhere 11 Demo"
    myConn.Open()
    myConn.Close()
End Sub

Connection pooling
Checking the connection state