数据库连接池配置

来源:互联网 发布:js实现360度全景图 编辑:程序博客网 时间:2024/06/05 11:45

1.数据库连接池配置文件

     在tomcat/conf/server.xml文件的  <GlobalNamingResources>标签中加入一个子标签<Resource>

<Resource name="jdbc/webdb" auth="Container"
   type="javax.sql.DataSource"                 //数据源类型
   driverClassName="com.mysql.jdbc.Driver"   //驱动程序
   url="jdbc:mysql://127.0.0.1:6789/webdb?characterEncoding=utf-8"  //数据库连接url
   username="root"    //数据库用户名
   password="admin"    //数据库密码
   maxActive="10"   //连接池最大连接数
   maxIdle="7"       //连接池最大空闲连接数
   maxWait="3000"     //暂时无法获得数据库连接的最大等待时间,单位:毫秒
   />

如下图:


2.把数据库连接池资源添加到上下文

     在tomcat/conf/context.xml文件的<Context>标签中加入一个子标签<ResourceLink >

     <ResourceLink name="jdbc/webdb" global="jdbc/webdb" type="javax.sql.DataSource" />

如下图:


3.使用数据库连接池连接数据库并往数据库写入数据

  以下是使用servlet技术来操作数据库

package rootLei;
import java.io.IOException;


import java.rmi.ServerException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.http.HTTPBinding;


public class DBServlet extends HttpServlet
{

protected java.sql.Connection conn = null;

//向数据库写入数据的方法
protected java.sql.ResultSet execSQL(String sql, Object... args)
throws Exception
{
java.sql.PreparedStatement pStmt = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++)
{
pStmt.setObject(i + 1, args[i]);
}
pStmt.execute();
return pStmt.getResultSet();
}

//servlet的主方法
protected void service(HttpServletRequest request, HttpServletResponse response)
throws  IOException, ServletException
{
try
{
if (conn == null)
{
javax.naming.Context ctx = new javax.naming.InitialContext(); //获取上下文ctx
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("java:/comp/env/jdbc/webdb");  //从上下文中获取数据源
conn = ds.getConnection(); //连接数据库
}

String sql = "insert into t_users(user_name,password_md5,email) values(?,?,?)";

                        userName = "";

             passwordMD5="";

email="";
execSQL(sql, userName,passwordMD5,email); //向数据库插入数据,
插入数据前首先要在Sql中建立相应的数据库和表
}
catch (Exception e)
{
                        System.out.println("错误:"+e.getMessage());
}
}

public void destroy()
{
try
{
if (conn != null)
conn.close();
}
catch (Exception ex)
{


}
}
}


0 0
原创粉丝点击