Chapter 20. The Python DB-APIContents:DB-API supports database-independent database access. The MySQL implementation of this API, MySQLdb, can be downloaded from http://dustman.net/andy/python/MySQLdb. It comes with a RedHat RPM Linux installer, a Win32 installer, and a Python script for other platforms. For those other platforms:
The MySQLdb module contains the standard DB-API methods and attributes as well as several proprietary methods and attributes. Proprietary APIs are marked with asterisks. 20.1. Module: MySQLdbThe entry point into the MySQL module is via the MySQLdb.connect( ) method. The return value from this method represents a connection to a MySQL database that you can use for all of your MySQL operations. 20.1.1. Module Attributes
SynopsisDefines the type of parameter placeholder in parameterized queries. DB-API supports many valid values for this attribute, but MySQLdb actually supports only format and pyformat. This attribute is largely meaningless to MySQL developers.
SynopsisSpecifies the level of thread safety supported by MySQLdb. Possible values are:
SynopsisMaps MySQL types from strings to the desired mapping type. This value is initialized with: { FIELD_TYPE.TINY : int, FIELD_TYPE.SHORT: int, FIELD_TYPE.LONG: long, FIELD_TYPE.FLOAT: float, FIELD_TYPE.DOUBLE: float, FIELD_TYPE.LONGLONG: long, FIELD_TYPE.INT24: int, FIELD_TYPE.YEAR: int } 20.1.2. Module Methods
Signatureconnection = MySQL.connect(params) SynopsisConnects to the MySQL database engine represented by the various connection keyword/value parameters. These parameters include:
This method returns a Python object representing a connection to a MySQL database. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); 20.1.4. Connection Methods
Signatureclose( ) SynopsisCloses the current connection to the database and releases any associated resources. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); connection.close( );
Signaturecommit( ) SynopsisCommits the current transaction by sending a COMMIT to MySQL. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); connection._transactional = 1; cursor = connection.cursor( ); cursor.execute("UPDATE TNAME SET COL = 1 WHERE PK = 2045"); cursor.execute("UPDATE TNAME SET COL = 1 WHERE PK = 3200"); connection.commit( ); connection.close( );
Signaturecursor = cursor( ) SynopsisCreates a cursor associated with this connection. Transactions involving any statements executed by the newly created cursor are governed by this connection. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); cursor = connection.cursor( ); cursor.execute("UPDATE TNAME SET COL = 1 WHERE PK = 2045"); connection.close( );
Signaturerollback( ) SynopsisRolls back any uncommitted statements. This works only if MySQL is set up for transactional processing in this context. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); connection._transactional = 1; cursor = connection.cursor( ); cursor.execute("UPDATE TNAME SET COL = 1 WHERE PK = 2045"); try: cursor.execute("UPDATE TNAME SET COL = 1 WHERE PK = 3200"); connection.commit( ); except: connection.rollback( ); connection.close( ); 20.1.5. Cursor Attributes
SynopsisSpecifies the number of rows to fetch at a time with the fetchmany( ) method call. By default, this value is set to 1. In other words, fetchmany( ) fetches one row at a time by default.
SynopsisDescribes a result column as a read-only sequence of seven-item sequences. Each sequence contains the following values: name, type_code, display_size, internal_size, precision, scale, and null_ok. 20.1.6. Cursor Methods
Signaturecallproc(procname [,parameters]) SynopsisThis method is not supported by MySQL.
Signatureclose( ) SynopsisCloses the cursor explicitly. Once closed, a cursor will throw a ProgrammingError if any operation is attempted on the cursor. Examplecursor = connection.cursor( ); cursor.close( );
Signaturecursor = execute(sql [,parameters]) SynopsisSends arbitrary SQL to MySQL for execution. If the SQL specified is parameterized, the optional second argument is a sequence or mapping containing parameter values for the SQL. Any results or other information generated by the SQL can then be accessed through the cursor. The parameters of this method may also be lists of tuples to enable you to perform multiple operations at once. This usage is considered deprecated as of the DB-API 2.0 specification. You should use the executemany( ) method instead. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); cursor = connection.cursor( ); cursor.execute('SELECT * FROM TNAME');
Signaturecursor.executemany(sql,parameters) SynopsisPrepares an SQL statement and sends it to MySQL for execution against all parameter sequences or mappings in the parameters sequence. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); cursor = connection.cursor( ); cursor.executemany("INSERT INTO COLOR ( COLOR, ABBREV ) VALUES (%s, %s )", (("BLUE", "BL"), ("PURPLE", "PPL"), ("ORANGE", "ORN")));
Signaturerows = cursor.fetchall( ) SynopsisFetches all remaining rows of a query result as a sequence of sequences. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); cursor = connection.cursor( ); cursor.execute("SELECT * FROM TNAME"); for row in cursor.fetchall( ): # process row
Signaturerows = cursor.fetchmany([size]) SynopsisFetches the next set of rows of a result set as a sequence of sequences. If no more rows are available, this method returns an empty sequence. If specified, the size parameter dictates how many rows should be fetched. The default value for this parameter is the cursor's arraysize value. If the size parameter is larger than the number of rows left, the resulting sequence will contain all remaining rows. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); cursor = connection.cursor( ); cursor.execute("SELECT * FROM TNAME"); rows = cursor.fetchmany(5);
Signaturerow = cursor.fetchone( ) SynopsisFetches the next row of a result set returned by a query as a single sequence. This method will return None when no more results exist. It will throw an error if the SQL executed is not a query. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); cursor = connection.cursor( ); cursor.execute("SELECT * FROM TNAME"); row = cursor.fetchone( ); print "Key: ", row[0]; print "Value: ", row[1];
Signatureid = cursor.insert_id( ) SynopsisReturns the last inserted ID from the most recent INSERT on an AUTO_INCREMENT field. Exampleconnection = MySQLdb.connect(host='carthage', user='test', passwd='test', db='test'); cursor = connection.cursor( ); cursor.execute("INSERT INTO TNAME (COL) VALUES (1)"); id = cursor.insert_id( ); Copyright © 2003 O'Reilly & Associates. All rights reserved. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|