J
jason.cipriani
I'm new to Java servlet development. I'm accessing a database via a
JNDI DataSource resource that I've defined in my servlet's context. I
have gotten it working using some code like this:
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/
mssql");
Connection conn = ds.getConnection();
PreparedStatement pstmt = conn.prepareStatement(stmt);
ResultSet rs = pstmt.executeQuery();
My question is, where is the most appropriate place to:
1. Construct a new InitialContext,
2. Look up the DataSource resource (call ctx.lookup),
3. Initialize db connection (call ds.getConnection).
And also I'm wondering about the most appropriate place to store the
InitialContext, DataSource, and Connection. My options, for each of
the above 3, are:
A. Init in servlet class constructor. Store item as class member.
B. Init when creating a new HTTP session. Store item as session
attribute.
C. Init as needed in servlet class methods. Store item as local
variable.
D. Maybe something else I'm not thinking of.
Can somebody help me match up my 1,2,3's with my A,B,C's?
Also when should I close the database connection? Do I even need to
worry about it, or will it automagically happen for me? I am using
connection pooling.
Thanks a lot,
Jason
JNDI DataSource resource that I've defined in my servlet's context. I
have gotten it working using some code like this:
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/
mssql");
Connection conn = ds.getConnection();
PreparedStatement pstmt = conn.prepareStatement(stmt);
ResultSet rs = pstmt.executeQuery();
My question is, where is the most appropriate place to:
1. Construct a new InitialContext,
2. Look up the DataSource resource (call ctx.lookup),
3. Initialize db connection (call ds.getConnection).
And also I'm wondering about the most appropriate place to store the
InitialContext, DataSource, and Connection. My options, for each of
the above 3, are:
A. Init in servlet class constructor. Store item as class member.
B. Init when creating a new HTTP session. Store item as session
attribute.
C. Init as needed in servlet class methods. Store item as local
variable.
D. Maybe something else I'm not thinking of.
Can somebody help me match up my 1,2,3's with my A,B,C's?
Also when should I close the database connection? Do I even need to
worry about it, or will it automagically happen for me? I am using
connection pooling.
Thanks a lot,
Jason