get Database Connection from Context - Java JNDI

Java examples for JNDI:Context

Description

get Database Connection from Context

Demo Code


//package com.java2s;

import java.sql.Connection;

import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getConnection());
    }//from ww  w  .  j a  v  a 2  s  .c o m

    public static Connection getConnection() throws SQLException {
        Connection con = null;
        Context context;
        try {
            context = new InitialContext();
            DataSource dataSource = (DataSource) context
                    .lookup("java:comp/env/jdbc/BettaServerDB");
            con = dataSource.getConnection();
        } catch (NamingException e) {
            e.printStackTrace();
        }

        return con;
    }
}

Related Tutorials