一 概念介绍:
1、连接池
Connection的取得和开放是代价比较高的处理,解决这个问题的方法是连接池。
连接池就是事先取得一定数量的Connection,程序执行处理的时候不是新建Connection,而是取得预先准备好的Connection的使用权。
2、DataSource
提供连接池机能的技术叫DataSource。 Javax.sql.DataSource
一般web服务器会提供。比如Tomcat5.5。
DataSource可以通过new来取得,但通常是通过 JNDI 用 lookup 取得。
3、JNDI (Java Naming and Directory Interface)
Java 命名和目录服务接口(Java Naming and Directory Interface,JNDI)。
命名服务: 可以类比为Session属性的Map的高级版。实现指定名字的对象的,取得和登录。一般Web服务器会提供。
目录服务: 和命名服务类似,但是对象的管理是层次性的。
在命名服务里登录的对象,可以用lookup()取得。
(PS:来源:http://www.cnblogs.com/nliao/p/3191201.html)
二 最基本的配置jdbc的方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import java.sql.Connection;
import java.sql.DriverManager;
public class DbConn {
private static String driver = "com.mysql.jdbc.Driver" ;
private static String url = "jdbc:mysql://127.0.0.1:3306/onlinefriend?useUnicode=true&characterEncoding=utf-8" ;
private static String user = "root" ;
private static String passwd = "root" ;
public static Connection getConnection(){
try {
//加载驱动
Class.forName(driver);
//连接数据库
Connection conn = DriverManager.getConnection(url,user,passwd);
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null ;
}
} |
三 通过JNDI连接池技术来配置jdbc
1 (在项目名)/WebContent/WEB-INF/ 新建 context.xml,具体内容为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<? xml version = "1.0" encoding = "UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd"> < Context >
< Resource name = "jdbc/onlinefriend"
auth = "Container" type = "javax.sql.DataSource" driverClassName = "com.mysql.jdbc.Driver" url = "jdbc:mysql://127.0.0.1:3306/onlinefriend?useUnicode=true&characterEncoding=utf-8"
username = "root" password = "root" maxActive = "100" maxIdle = "30" maxWait = "10000" />
</ Context >
|
2 在web应用下的 web.xml 增加一个节点(这一步可以省略,这里配置主要是可以使相关配置信息更加稳定)
1
2
3
4
5
6
|
< resource-ref >
< description >DBConn</ description >
< res-ref-name >jdbc/onlinefriend</ res-ref-name >
< res-type >javax.sql.DataSource</ res-type >
< res-auth >Container</ res-auth >
</ resource-ref >
|
3 配置数据库连接方法类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import java.sql.Connection;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DbConn {
public static Connection getConnection(){
try {
InitialContext context = new InitialContext();
DataSource dSource = (DataSource) context.lookup( "java:comp/env/jdbc/onlinefriend" );
Connection conn = dSource.getConnection();
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null ;
}
} |
网友评论