servlet JDBC mysql数据库连接池

具体操作过程:

1、配置全局数据库连接池

\conf\server.xml文件中找到标签,添加下列配置:

2、下载JDBC驱动的jar包,放在tomcat的lib目录下
3、在创建的webdemo工程中web.xml文件中增加下列配置:


 	jdbc/webdb
 	javax.sql.DataSource
 	Container
 	Shareable
 

4、在webdemo工程的META-INF目录下增加一个context.xml文件,内容如下:



  
  
  
  
  


5、访问数据库事例java文件

package chapter4;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Helloworld extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		try
		{
			javax.naming.Context ctx = new javax.naming.InitialContext();
			javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup("java:/comp/env/jdbc/webdb");
			
			
			Connection conn = ds.getConnection();
			PreparedStatement pst = conn.prepareStatement("SELECT * FROM t_dictionary");
			ResultSet rs = pst.executeQuery();
			StringBuilder table = new StringBuilder();
			table.append("");
			table.append("");
			while(rs.next())
			{
				table.append("");
			}
			table.append("
eg-namech-name
"+rs.getString("english")+""); table.append(rs.getString("chinese")+"
"); out.println(table.toString()); pst.close(); } catch(Exception e) { out.println(e.getMessage()); } } }


差不多servlet访问mysql数据库能测试成功。

 

你可能感兴趣的:(java,web开发)