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( );
Get Managing & Using MySQL, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.