How to Open and Close a Database Connection Using Python

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:

The following code sample opens and closes a connection to the SAP Sybase IQ 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="<user_id>",
                        password="<password>" )
# 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="Sybase IQ Demo" )

# Close the connection
con.close()