Manage multiple database connections
The SQLConnectionHash class is useful to store in a wrapped dictionary all the local database connection you may need in an AIR application.
The class implementation is quite simple, trough the following methods you manage all the connections
- addConnection(name:String, connection:SQLConnection):void Add a connection to the hashmap checking if a connection with this name already exists
- getConnection(name:String) : SQLConnection Retrieves a managed SQLConnection instance based on the
- closeConnection(name:String):void Closes the connection to the previously cached SQLConnection instance and remove it from the map
The class dispatches a bunch of events to get all the information you need about the operations performed (i.e. name of the connection and connection instance).
A sample usage of this class is
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import com.gnstudio.nabiro.air.data.events.SQLHashEvent;
import com.gnstudio.nabiro.air.data.utils.SQLConnectionHash;
private var sqlHash:SQLConnectionHash
override protected function childrenCreated():void{
super.childrenCreated();
sqlHash = new SQLConnectionHash();
sqlHash.addEventListener(SQLHashEvent.CONNECTION_ADDED, onConnectionAdded);
sqlHash.addEventListener(SQLHashEvent.CONNECTION_CLOSE_ERROR, onConnectionCloseError);
sqlHash.addEventListener(SQLHashEvent.CONNECTION_CLOSE_SUCCESS, onConnectionCloseSuccess);
sqlHash.addEventListener(SQLHashEvent.EMPTY_CONNECTION_CREATED, onConnectionCreated);
var file:File = File.applicationStorageDirectory.resolvePath("data.db");
var sqlConnection:SQLConnection = new SQLConnection()
sqlConnection.addEventListener(SQLEvent.OPEN, onDataBaseOpened);
sqlConnection.open(file);
}
private function onDataBaseOpened(e:SQLEvent):void{
sqlHash.addConnection("one", e.target as SQLConnection);
sqlHash.addConnection("two", e.target as SQLConnection);
sqlHash.addConnection("thre", e.target as SQLConnection);
sqlHash.getConnection("four");
sqlHash.closeConnection("one")
}
private function onConnectionAdded(e:SQLHashEvent):void{
trace(e.type, e.connection, e.connectionName)
}
private function onConnectionCloseSuccess(e:SQLHashEvent):void{
trace(e.type, e.connection, e.connectionName)
}
private function onConnectionCreated(e:SQLHashEvent):void{
trace(e.type, e.connection, e.connectionName)
}
private function onConnectionCloseError(e:SQLHashEvent):void{
trace(e.type, e.connectionName)
}
]]>
</mx:Script>
</mx:WindowedApplication>