Connecting Through a DataSource
Data sources in the database context of Apache OpenOffice API offer two methods to establish a connection, a non-interactive and an interactive procedure. Use the com.sun.star.sdbc.XDataSource interface to connect. It consists of:
// establish connection
com::sun::star::sdbc::XConnection getConnection(
[in] string user, [in] string password)
// timeout for connection failure
void setLoginTimeout( [in] long seconds)
long getLoginTimeout()
If a database does not support logins, pass empty strings to getConnection()
. For instance, use getConnection()
against dBase data sources like Bibliography:
XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface(
XNameAccess.class, _rMSF.createInstance("com.sun.star.sdb.DatabaseContext"));
// we use the Bibliography data source
XDataSource xDS = (XDataSource)UnoRuntime.queryInterface(
XDataSource.class, xNameAccess.getByName("Bibliography"));
// simple way to connect
XConnection xConnection = xDS.getConnection("", "");
However, if the database expects a login procedure, hard code the user and password, although this is not advisable. Data sources support an advanced login concept. Their interface com.sun.star.sdb.XCompletedConnection starts an interactive login, if necessary:
com::sun::star::sdbc::XConnection connectWithCompletion(
[in] com::sun::star::task::XInteractionHandler handler)
When you call connectWithCompletion()
, Apache OpenOffice API shows the common login dialog to the user if the data source property IsPasswordRequired
is true. The login dialog is part of the com.sun.star.sdb.InteractionHandler provided by the global service factory.
// logs into a database and returns a connection
// expects a reference to the global service manager
com.sun.star.sdbc.XConnection logon(XMultiServiceFactory _rMSF) throws com.sun.star.uno.Exception {
// retrieve the DatabaseContext and get its com.sun.star.container.XNameAccess interface
XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface(
XNameAccess.class, _rMSF.createInstance("com.sun.star.sdb.DatabaseContext"));
// get an Adabas D data source Ada01 generated in the GUI
Object dataSource = xNameAccess.getByName("Ada01");
// create a com.sun.star.sdb.InteractionHandler and get its XInteractionHandler interface
Object interactionHandler = _rMSF.createInstance("com.sun.star.sdb.InteractionHandler");
XInteractionHandler xInteractionHandler = (XInteractionHandler)UnoRuntime.queryInterface(
XInteractionHandler.class, interactionHandler);
// query for the XCompletedConnection interface of the data source
XCompletedConnection xCompletedConnection = (XCompletedConnection)UnoRuntime.queryInterface(
XCompletedConnection.class, dataSource);
// connect with interactive login
XConnection xConnection = xCompletedConnection.connectWithCompletion(xInteractionHandler);
return XConnection;
}
Content on this page is licensed under the Public Documentation License (PDL). |