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.

 To connect to a SQL Anywhere database
  1. Allocate an SAConnection object.

    The following C# 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 12 Demo"

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

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

  3. Open a connection to the database.

    The following code attempts to connect to a database. It automatically starts 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 = txtConnectString.Text;
        _conn.Open();
  5. Close the connection to the database. Connections to the database stay open until they are explicitly closed using the Close method.

    _conn.Close();

For more information, see SAConnectionStringBuilder class and ConnectionName property.

 Visual Basic connection example

Connection pooling
Checking the connection state