Opening and closing a connection

Generally, you open a single connection to a database and then perform all the required operations through it by executing a sequence of SQL statements. To open a connection, you use the connect method. The return value is a handle to the database connection that you use to perform subsequent operations on that connection.

The parameters to the connect method are specified as a series of keyword=value pairs delimited by commas.

sqlanydb.connect( keyword=value, ...)

Some common connection parameters are as follows:

  • DataSourceName="dsn"   A short form for this connection parameter is DSN="dsn". An example is DataSourceName="SQL Anywhere 12 Demo".

  • UserID="user-id"   A short form for this connection parameter is UID="user-id". An example is UserID="DBA".

  • Password="passwd"   A short form for this connection parameter is PWD="passwd". An example is Password="sql".

  • DatabaseFile="db-file"   A short form for this connection parameter is DBF="db-file". An example is DatabaseFile="demo.db".

The following code sample opens and closes a connection to the SQL Anywhere sample database. You must start the database server and sample database before running this script.

import sqlanydb

# Create a connection object
con = sqlanydb.connect( userid="DBA",
                        password="sql" )
# Close the connection
con.close()

To avoid starting the database server manually, you could use a data source that is configured to start the server. This is shown in the following example.

import sqlanydb

# Create a connection object
con = sqlanydb.connect( DSN="SQL Anywhere 12 Demo" )

# Close the connection
con.close()
 See also