Changes between Version 9 and Version 10 of TracDev/DatabaseApi
- Timestamp:
- Apr 15, 2009, 11:49:38 PM (15 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
TracDev/DatabaseApi
v9 v10 12 12 == Accessing the Database == 13 13 14 Code accessing the database in Trac go through this layer simply by using the {{{Environment}}} method {{{get_db_cnx()}}} :14 Code accessing the database in Trac go through this layer simply by using the {{{Environment}}} method {{{get_db_cnx()}}} in order to get a pooled database connection. A database cursor can be obtained from the pooled database connection, and the code uses the cursor in conjunction with SQL statements to implement the behavior. 15 15 16 16 {{{ 17 17 #!python 18 18 from trac.env import Environment 19 def myFunc(): 20 env = Environment('/path/to/projenv') 21 db = env.get_db_cnx() 22 cursor = db.cursor() 23 # Execute some SQL statements 19 24 20 env = Environment('/path/to/projenv') 21 db = env.get_db_cnx() 22 cursor = db.cursor() 23 # Execute some SQL statements 24 25 db.commit() 25 db.commit() 26 return 26 27 }}} 27 28 … … 34 35 35 36 ''The connection URI syntax has been designed to be compatible with that provided by [http://sqlobject.org/docs/SQLObject.html#declaring-the-class SQLObject] (see also the Wiki page on SQLObject [http://wiki.sqlobject.org/connections.html connections]). The only supported URI schemes at this point are {{{sqlite}}} and {{{postgres}}}.'' 37 38 === Pooled Connections === 39 40 The {{{Environment}}} method {{{get_db_cnx()}}} returns a connection from the pool of connections. This connection needs to be returned, and Trac is written so that the return will happen automatically by the garbage collector if the code is written to follow a simple rule. When the garbage collector determines the pooled database connection is no longer being used, it's __del__ method will return the pooled connection to the pool for reuse. If you have set a lexical variable in the function's body to the pooled connection, this typically occurs when the function is returning. In the example above of {{{myFunc}}} it occurs at the return statement since {{{db}}} is a variable local to {{{myFunc}}} 36 41 37 42 == Rules for DB API Usage ==