JNDI数据源配置
导入jar
mysql-connector-java-5.1.49.jar
编写servlet
package com.zb.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
@WebServlet("/ds")
public class TestServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
//获得Servlet容器对象
Context context = new InitialContext();
//从容器中取出内容java:/comp/env/+JDNIname
DataSource dataSource = (DataSource)context.lookup("java:/comp/env/mySqlDataSource");
//通过JNDI获取的数据源获取数据库连接
Connection conn = dataSource.getConnection();
System.out.println(conn.prepareStatement(" DELETE FROM user_info ").executeUpdate()>0?"执行成功":"执行失败");
} catch (NamingException e) {
System.out.println(e);
System.out.println("获取JNDI容器异常");
} catch (SQLException e) {
System.out.println(e);
System.out.println("获得数据库连接异常");
}
}
}