Connecting to a database

Use C# code to connect to a SQL Anywhere database.

Prerequisites

Create a Visual Studio application that implements the ADO.NET API.

Context and remarks

Many.

 Task
  1. Creates an SAConnection object named conn with the following code:

    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 %SQLANYSAMP12%\SQLAnywhere\ADO.NET\TableViewer and Understanding the Table Viewer sample project.

  2. Specify the connection string used to connect to the database using the following code:

    _conn.ConnectionString = "Data Source=SQL Anywhere 12 Demo"

    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.

    _conn.Close();

    Connections to the database stay open until they are explicitly closed using the Close method.

Results

The application opens a connection to the database.

Next

Interface with the SAConnection object to perform database operations in your .NET application.

Example

The following Visual Basic code creates a method that 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 12 Demo"
    myConn.Open()
    myConn.Close()
End Sub

 See also

Connection pooling
Connection state