Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional Beginning Python - From Novice to Professional

16.01.2014 Views

CHAPTER 13 ■ DATABASE SUPPORT 287 insert %s where you want to splice in parameters, for example. The value 'pyformat' indicates extended format codes, as used with dictionary splicing, such as %(foo)s. In addition to these Pythonic styles, there are three ways of writing the splicing fields: 'qmark' means that question marks are used, 'numeric' means fields of the form :1 or :2 (where the numbers are the numbers of the parameters), and 'named' means fields like :foobar, where foobar is a parameter name. Exceptions The API defines several exceptions, to make fine-grained error handling possible. However, they’re defined in a hierarchy, so you can also catch several types of exceptions with a single except block. (Of course, if you expect everything to work nicely, and you don’t mind having your program shut down in the unlikely event of something going wrong, you can just ignore the exceptions altogether.) The exception hierarchy is shown in Table 13-2. The exceptions should be available globally in the given database module. For more in-depth descriptions of these exceptions, please see the API specification (the PEP mentioned previously). Table 13-2. Exceptions Specified in the DB-API Exception Superclass Description StandardError Generic superclass of all exceptions Warning StandardError Raised if a nonfatal problem occurs Error StandardError Generic superclass of all error conditions InterfaceError Error Errors relating to the interface, not the database DatabaseError Error Superclass for errors relating to the database DataError DatabaseError Problems related to the data; e.g., values out of range OperationalError DatabaseError Errors internal to the operation of the database IntegrityError DatabaseError Relational integrity compromised; e.g., key check fails InternalError DatabaseError Internal errors in the database; e.g., invalid cursor ProgrammingError DatabaseError User programming error; e.g., table not found NotSupportedError DatabaseError An unsupported feature (e.g., rollback) requested Connections and Cursors In order to use the underlying database system, you must first connect to it. For this you use the aptly named function connect. It takes several parameters; exactly which depends on the database. The API defines the parameters in Table 13-3 as a guideline. It recommends that they be usable as keyword arguments, and that they follow the order given in the table. The arguments should all be strings.

288 CHAPTER 13 ■ DATABASE SUPPORT Table 13-3. Common Parameters of the connect Function Parameter Name Description Optional? dsn Data source name. Specific meaning database dependent. user User name. Yes password User password. Yes host Host name. Yes database Database name. Yes No You’ll see specific examples of using the connect function in the section “Getting Started” later in this chapter, as well as in Chapter 26. The connect function returns a connection object. This represents your current session with the database. They support the methods shown in Table 13-4. Table 13-4. Connection Object Methods Method Name close() commit() rollback() cursor() Description Close the connection. Connection object and its cursors are now unusable. Commit pending transactions, if supported. Otherwise do nothing. Roll back pending transactions. (May not be available.) Return a cursor object for the connection. The rollback function may not be available, because not all databases support transactions. (Transactions are just sequences of actions.) If it exists, it will “undo” any transactions that have not been committed. The commit function is always available, but if the database doesn’t support transactions, it doesn’t actually do anything. If you close a connection and there are still transactions that have not been committed, they will implicitly be rolled back— but only if the database supports rollbacks! So if you don’t want to rely on this, you should always commit before you close your connection. If you commit, you probably don’t have to worry too much about closing your connection; it’s automatically closed when it’s garbage collected. If you want to be on the safe side, though, a call to close won’t cost you that many keystrokes . . . The cursor function leads us to another topic: cursor objects. You use cursors to execute SQL queries and to examine the results. Cursors support more methods than connections, and probably will be quite a bit more prominent in your programs. Table 13-5 gives an overview of the cursor methods, and Table 13-6 gives an overview of the attributes.

288 CHAPTER 13 ■ DATABASE SUPPORT<br />

Table 13-3. Common Parameters of the connect Function<br />

Parameter Name Description Optional?<br />

dsn<br />

Data source name. Specific meaning<br />

database dependent.<br />

user User name. Yes<br />

password User password. Yes<br />

host Host name. Yes<br />

database Database name. Yes<br />

No<br />

You’ll see specific examples of using the connect function in the section “Getting Started”<br />

later in this chapter, as well as in Chapter 26.<br />

The connect function returns a connection object. This represents your current session<br />

with the database. They support the methods shown in Table 13-4.<br />

Table 13-4. Connection Object Methods<br />

Method Name<br />

close()<br />

commit()<br />

rollback()<br />

cursor()<br />

Description<br />

Close the connection. Connection object and its cursors are now unusable.<br />

Commit pending transactions, if supported. Otherwise do nothing.<br />

Roll back pending transactions. (May not be available.)<br />

Return a cursor object for the connection.<br />

The rollback function may not be available, because not all databases support transactions.<br />

(Transactions are just sequences of actions.) If it exists, it will “undo” any transactions<br />

that have not been committed. The commit function is always available, but if the database<br />

doesn’t support transactions, it doesn’t actually do anything. If you close a connection and<br />

there are still transactions that have not been committed, they will implicitly be rolled back—<br />

but only if the database supports rollbacks! So if you don’t want <strong>to</strong> rely on this, you should<br />

always commit before you close your connection. If you commit, you probably don’t have <strong>to</strong><br />

worry <strong>to</strong>o much about closing your connection; it’s au<strong>to</strong>matically closed when it’s garbage<br />

collected. If you want <strong>to</strong> be on the safe side, though, a call <strong>to</strong> close won’t cost you that many<br />

keystrokes . . .<br />

The cursor function leads us <strong>to</strong> another <strong>to</strong>pic: cursor objects. You use cursors <strong>to</strong> execute<br />

SQL queries and <strong>to</strong> examine the results. Cursors support more methods than connections, and<br />

probably will be quite a bit more prominent in your programs. Table 13-5 gives an overview of<br />

the cursor methods, and Table 13-6 gives an overview of the attributes.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!