Java如何使用JNDI获取数据库连接或数据源?
package org.nhooo.example.jndi;import javax.naming.InitialContext;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JNDITestServlet extends HttpServlet implements Servlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// doGet方法的此实现向我们展示了一个使用示例
// 在getConnection()方法中获得的conn。
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
Connection conn = getConnection();
if (conn != null) {
try {
// 从Oracle数据库获取当前日期时间的查询
String sql = "SELECT SYSDATE FROM DUAL";
PreparedStatement statement = conn.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
Date date = rs.getDate("SYSDATE");
writer.println("The current date is " + format.format(date));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (!conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/**从注册的数据源中获取一个数据库连接,servlet容器。要注册JNDI数据源,您应该这样做,参考你的servlet容器文档。
*
* @return a database connection
*/
private Connection getConnection() {
Connection connection = null;
try {
InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context
.lookup("jdbc/DataSource");
connection = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
以上是 Java如何使用JNDI获取数据库连接或数据源? 的全部内容, 来源链接: utcz.com/z/315898.html