Connect to the Database from Code

This example shows how to connect to the XML or SQL database from code. For creating and showing the viewer from code you will need to call the StiViewerFx.initialize() static method. Call this method in the initialize event of the application. Also load a report template file and assign it to the reportString variable:

<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
minWidth="1024" minHeight="768" backgroundColor="#e8e8e8"
initialize="onInitialize()" xmlns:viewer="stimulsoft.viewer.*">

...

private function onInitialize(): void
{
StiViewerFx.initialize();

var request: URLRequest = new URLRequest(demoFile);
var loader: URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onLoadComplete);
loader.load(request);
}

private function onLoadComplete(event: Event): void
{
var loader: URLLoader = event.target as URLLoader;
reportString = loader.data as String;
}


To create the XML data connection, you need to use the StiXmlDatabase class. In the parameters of the constructor you should pass the data connection name, part to the XSD schema and path to the XML data files. Then use the report.dictionary.databases.add() method for adding the created data connection object to the report. If you need to clear the existing data connections in the report, you can use the report.dictionary.databases.clear() method:

private function onConnectToXMLClick(): void
{
// Create new report object
var report: StiReport = new StiReport();
// Load report from XML string
report.loadReportFromString(reportString);
// Create new XML database with same name "Demo"
var database: StiXmlDatabase = new StiXmlDatabase("Demo", "reports/data/Demo.xsd", "reports/data/Demo.xml");
// Clear all existing databases in report
report.dictionary.databases.clear();
// Add database to report
report.dictionary.databases.add(database);
// Show report in Viewer dialog window
report.showDialog();
}


To create the MySQL data connection the actions will be same, except that you need to use the StiMySqlDatabase class. In the parameters of the constructor you should pass the data connection name and alias, connection string and flag for password management:

private function onConnectToMySqlClick(): void
{
// Create new report object
var report: StiReport = new StiReport();
// Load report from XML string
report.loadReportFromString(reportString);
// Create new MySql database with same name "Demo"
var database: StiMySqlDatabase = new StiMySqlDatabase("Demo", "",
"Server=localhost;Port=3306;Database=db_name;Uid=root;Pwd=;", false);
// Clear all existing databases in report
report.dictionary.databases.clear();
// Add database to report
report.dictionary.databases.add(database);
}


In the screenshot below you can see the result of the sample code.

Connect to the Database from Code