6.4 Multiple Database Connections

In the previous article we've seen how to configure a Zone in the server in order to connect to a database source.
This is done by adding simple XML tags in the main config.xml file, specifying all the necessary connection informations.
There's also a dynamic way of setting up a connection to a database server which allows to handle multiple data sources in your extensions.

» Creating new connections using code

The following is an example of server side Actionscript code that creates a new database connection:

function testDB()
{
   var driverName = "org.gjt.mm.mysql.Driver"
   var connString = "jdbc:mysql://localhost:3306/myDatabase"
   var usrName = "login"
   var pword = "password"
   var connName = "myDbConnection"
   var maxActive = 10
   var maxIdle = 10
   var exhaustedAction = "fail"
   var blockTime = 5000
   
   dbase2 = new __db.DbManager(   driverName,
                           connString,
                           usrName,
                           pword,
                           connName,
                           maxActive,
                           maxIdle,
                           exhaustedAction,
                           blockTime
                        )
   
   var sql = "SELECT nick,pass FROM users ORDER BY nick"      
      
   var queryRes = dbase2.executeQuery(sql)
   
   // etc... etc...
}
 

The code is pretty straightforward: we prepare the necessary parameters to setup a connection (as seen in the previous article) and we pass them to the __db.DbManager constructor which returns a database manager object that can be used to interact with the database.

We recommend to create these connections once in the init() method of your extension and keeping a global reference to the database manager object returned.

The following is a simple example of how it should be done:

// Let's declare these variables in the global scope
// they will keep the reference to that databaseManager objects
var db1, db2

// Extension initialization method
function init()
{
	// Add your initialization code here
	// ...
	
	// Set up the database connections
	setupDbConnections()
	
	// From now on, we can refere to db1 and db1 all over in our code.
}

// Create the connections
function setupDbConnections()
{
    db1 = __db.DbManager( ... )
    db2 = __db.DbManager( ... )
}
 

 


doc index