The Database Connection
The entry point into
DB-API is really the only
part of the API tied to a particular database engine. By convention,
all modules supporting DB-API are named after the database they
support with a db extension. The MySQL
implementation is thus called MySQLdb. Similarly, the Oracle
implementation is called oracledb and the Sybase implementation
sybasedb. Each module contains a connect(
)
method that
returns a DB-API connection object. This method returns an object
that has the same name as the module:
import MySQLdb;
conn = MySQLdb.connect(host='carthage', user='test',
passwd='test', db='test');This example connects using the username/password pair
test/test to the MySQL database
test hosted on the machine
carthage. In addition to these four arguments, you
can specify a custom port, the location of a Unix socket to use for
the connection, and an integer representing client connection flags.
All arguments must be passed to connect( ) as
keyword/value pairs, as in the example above.
The API for a connection object is very simple. You basically use it to gain access to cursor objects and manage transactions. When you are done, you should close the connection:
conn.close( );
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access