prepare Query via InitialContext - Java java.sql

Java examples for java.sql:PreparedStatement

Description

prepare Query via InitialContext

Demo Code


//package com.java2s;
import java.sql.Connection;
import java.sql.PreparedStatement;

import java.sql.SQLException;

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

public class Main {
    static PreparedStatement preparedStatement = null;
    static Connection c = null;

    public static PreparedStatement prepareQuery(String query) {

        try {/*  w  w  w .j av  a 2  s. com*/
            // getting the datasource declared in web.xml
            InitialContext initCtx = new InitialContext();
            DataSource dataSource = (DataSource) initCtx
                    .lookup("java:comp/env/jdbc/loctagDB");

            // getting a connection from the DataSource/connection pool
            c = dataSource.getConnection();
            preparedStatement = c.prepareStatement(query);

        }

        catch (SQLException e) {
            e.printStackTrace();
            return null;
        } catch (NamingException e) {
            e.printStackTrace();
            return null;
        }

        return preparedStatement;

    }
}

Related Tutorials