Book Image

WildFly Configuration, Deployment, and Administration

Book Image

WildFly Configuration, Deployment, and Administration

Overview of this book

Table of Contents (19 chapters)
WildFly Configuration, Deployment, and Administration Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Connecting to a database


To allow your application to connect to a database, you will need to configure your server by adding a datasource. Upon server startup, each datasource is prepopulated with a pool of database connections. Applications acquire a database connection from the pool by doing a JNDI lookup and then calling getConnection(). Take a look at the following code:

Connection result = null;
try {
    Context initialContext = new InitialContext();
    DataSource datasource = (DataSource)initialContext.lookup("java:/MySqlDS");
    result = datasource.getConnection();
} catch (Exception ex) {
    log("Cannot get connection: " + ex);}

After the connection has been used, you should always call connection.close() as soon as possible. This frees the connection and allows it to be returned to the connection pool—ready for other applications or processes to use.

Releases prior to JBoss AS 7 required a datasource configuration file (ds.xml) to be deployed with the application. Ever since the...