Before you can carry out any operations on the data, your application must connect to the database. This section describes how to write code to connect to an Adaptive Server database.
For more information, see “AseConnection class” and “ConnectionString property”.
Connecting to an Adaptive Server database
Allocate an AseConnection object.
The following code creates an AseConnection object named “conn.”
For C#:
AseConnection conn = new AseConnection();
For Visual Basic .NET:
Dim conn As New AseConnection()
You can have more than one connection to a database from your application. Some applications use a single connection to an Adaptive Server database and keep the connection open all the time. To do this, you can declare a global variable for the connection.
For C#:
private AseConnection_conn;
For Visual Basic .NET:
Private _conn As AseConnection
For more information, see the code for the Table Viewer sample in <install dir>\Samples and “Understanding the Table Viewer sample project”.
Specify the connection string used to connect to the database:
For C#:
AseConnection conn = new AseConnection( "Data Source=’mango’;Port=5000;" + "UID=’sa’;PWD='';" + "Database='pubs2';" );
where “mango” is the host name where the database server is running.
For Visual Basic .NET:
Dim conn As New AseConnection(_ "Data Source=’mango’,Port=5000," +_ "UID=’sa’;PWD='''';" + _ "Database='pubs2';")
For a complete list of connection parameters, see “AseConnection constructors”.
Open a connection to the database using the following code:
For C#:
conn.Open();
For Visual Basic .NET:
conn.Open()
Catch connection errors.
Your application should be designed to catch any errors that occur when it attempts to connect to the database. The following code demonstrates how to catch an error and display its message.
For C#:
try { _conn = new AseConnection( txtConnectString.Text ); _conn.Open(); } catch( AseException ex ) { MessageBox.Show( ex.Message, "Failed to connect"); }
For Visual Basic .NET:
Try _conn = New AseConnection(_ txtConnectionString.Text) _conn.Open() Catch ex As AseException MessageBox.Show(_ ex.Message,_ "Failed to connect") End Try
Alternately, you can use the ConnectionString property to set the connection string, rather than passing the connection string when the AseConnection object is created.
For C#:
AseConnection conn = new AseConnection(); conn.ConnectionString = "Data Source='mango';" + "Port=5000;" + "UID='sa';" + "PWD='';" + "Database='pubs2';" ;
For Visual Basic .NET:
Dim conn As New AseConnection() conn.ConnectionString = "Data Source='mango';" + _ "Port=5000;" + _ "UID='sa';" + _ "PWD='';" + _ "Database='pubs2';"
where “mango” is the name of the database server.
Close the connection to the database. Connections to the database stay open until they are explicitly closed using the conn.Close() method.