当前位置:   article > 正文

java配置使用数据源_java.sql.datasource

java.sql.datasource

1. 数据源的定义:

数据源是数据库连接池里面的概念,连接池就是指当服务器启动时,先建立几个连接,在应用需要与数据库连接时,就从连接池里获取,使用完以后,不是将连接断掉,而是放回到池里面,这样就减少了数据连接创建的次数,大大提高了连接性能。而数据源就是给服务器一个配置信息,然服务器就知道怎么使用JDBC驱动,比如url参数,数据库实例名、用户名与密码等等。Java中的数据源就是javax.sql.DataSource。DataSource的创建可以有不同的实现,下面以mysql为例介绍几种常见DataSource的创建方法:

导入jar包:commons-dbcp.jar和commons-pool.jar和mysql-connector-java-5.1.39-bin.jar

推荐网址:

http://blog.csdn.net/peichuangaoling/article/details/45893391

http://blog.csdn.net/navy_xue/article/details/13090945

2. 配置数据库连接池使用之JNDI的方式


2.1 JNDI:

JNDI就是(JavaNaming and Directory IntefaceJava名称目录接口。

JNDI的作用:就是将资源引入到服务器中。可以将JNDI当成一个仓库。将Java对象放入到JNDI中去。


2.2 数据源的由来:

java开发中,使用JDBC操作数据库的几个步骤:

1.使用Class.forName(类的全路径名称):用于加载数据库驱动程序。

2.获得数据库的Connection连接对象。DriverManager.getConnection()

3.操作数据库:查询数据库,或者更新数据库内容,

4.关闭数据库连接:使用close方法。

注意:每次获取一个数据库连接的要经过这4个步骤,但是其中【1】,【2】,【4】是所有操作数据库的公共操作,只有【3】是操作数据库的不同步骤。并且获得数据库的connection对象和关闭数据库的连接都是要一定的时间。造成性能较差。

如果我们一开始就有已经创建好了多个connection对象,放在一个公共地方,当有一个连接数据库的请求,就从这个公共地方中取出一个connection,操作数据库,操作完成数据库,不关闭connection,而是放入到公共仓库中去,这就出现了数据库连接池的东西,就是存放多个Connection对象的地方。


2.3 使用JNDI配置数据数据库连接池有两种方式(全局JNDI配置和非全局JNDI配置)

如果需要配置全局的 Resource,则在server.xmlGlobalNamingResources节点里加入Resource,再在Context节点里加入ResourceLink的配置。

    全局的resource只是为了重用,方便所有该tomcat下的web工程的数据源管理,但如果你的tomcat不会同时加载多个web工程,也就是说一个tomcat只加载一个web工程时,是没有必要配置全局的resource的。

每个web工程一个数据源:

$CATALINA_HOME/conf/context.xml的根节点Context里加入Resource配置。这种配置方法,你在context.xml配置了一个数据源,但Tomcat中有同时运行着5个工程,那了就坏事儿了,这个在Tomcat启动时数据源被创建了5份,每个工程1份数据源。连接数会是你配置的参数的5倍。

只有在你的Tomcat只加载一个web工程时,才可以直接以context.xml配置数据源。


2.3.1 全局JNDI配置

在Tomacat的conf/context.xml中的内容:

  1. <context>
  2. <WatchedResource>WEB-INF/web.xml</WatchedResource>
  3. <!-- 配置mysql数据库的连接池 -->
  4. <Resource name="jdbc/mysql"
  5. author="Container"
  6. type="javax.sql.DataSource"
  7. maxActive="4"
  8. maxIdle="2"
  9. maxWait="10000"
  10. username="root"
  11. password="root"
  12. driverClassName="com.mysql.jdbc.Driver"
  13. url="jdbc:mysql://localhost:3306/mysqltest" />
  14. </context>


2.3.2 非全局JNDI配置

他只针对某一个Web项目的数据源的配置

1.导入要链接数据库的jar包文件。

例如sqlserver导入:sqljdbc4.jar

Oracle导入:ojdbc14.jar

配置Oracle数据库的JNDI数据源

  1. <Resource
  2. name="jdbc/oracle"
  3. auth="Container"
  4. type="javax.sql.DataSource"
  5. maxActive="100"
  6. maxIdle="30"
  7. maxWait="10000"
  8. username="lead_oams"
  9. password="p"
  10. driverClassName="oracle.jdbc.driver.OracleDriver"
  11. url="jdbc:oracle:thin:@192.168.1.229:1521:lead"/>

 

配置SQLServer数据库的JNDI数据资源

  1. <Resource
  2. name="jdbc/sqlserver"
  3. auth="Container"
  4. type="javax.sql.DataSource"
  5. maxActive="100"
  6. maxIdle="30"
  7. maxWait="10000"
  8. username="sa"
  9. password="123456"
  10. driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
  11. url="jdbc:sqlserver://192.168.1.51:1433;DatabaseName=demo"/>
  12. </Context>

 

MySQL导入:mysql-connector-java-5.0.8.jar

配置MySQL数据库的JNDI数据资源:

  1. <Resource name="jdbc/mysql"
  2. author="Container"
  3. type="javax.sql.DataSource"
  4. maxActive="100"
  5. maxIdle="30"
  6. maxWait="10000"
  7. username="root"
  8. password="root"
  9. driverClassName="com.mysql.jdbc.Driver"
  10. url="jdbc:mysql://localhost:3306/mysqltest" />

 

2.JNDI中配置数据库的连接池:

2):在web项目的META-INF下 建立context.xml文件

context.xml内容:

<?xml version="1.0" encoding="UTF-8"?>

   <Context>

      <Resource name="jdbc/mysql"

        author="Container"

        type="javax.sql.DataSource"

        maxActive="100"

        maxIdle="30"

        maxWait="10000"

        username="root"

        password="root"

        driverClassName="com.mysql.jdbc.Driver"

        url="jdbc:mysql://localhost:3306/mysqltest" />

  </Context>


说明:

上文中的设置的 maxActive="4"说明可以最大连接的个数为4个,再建立连接,则出现异常。

maxIdle="2"说明当关闭数据库时(不是真正的断开连接,而是归还连接池中)连接池中最大可以有空闲的连接数为2个。

若是再有建立连接,此时若连接池中没有空闲的连接,但是又没有达到maxActive并发的最大连接数,则在连接池中建立连接。

 

3): Tomcat的conf/server.xml中配置

找到:



配置

  1. <Resource name="jdbc/mysql"
  2. author="Container"
  3. type="javax.sql.DataSource"
  4. maxActive="100"
  5. maxIdle="30"
  6. maxWait="10000"
  7. username="root"
  8. password="liukunlun"
  9. driverClassName="com.mysql.jdbc.Driver"
  10. url="jdbc:mysql://loaclhost:3306/fuxi" />

如图:



然后Tomcat的conf/context.xml中配置 <ResourceLink name="jdbc/mysql" global="jdbc/mysql" type="javax.sql.DataSource"/>  如图:


上诉3个中法配置完成后最后都要配置web.xml内容  (web应用中引用JNDI资源) 

  1. <resource-ref>
  2. <!-- 对该资源的描述语言 -->
  3. <description> dbcpconnect</description>
  4. <!-- 引用的资源名,必须与context.xml中的名字一致 -->
  5. <res-ref-name> jdbc/mysql</res-ref-name>
  6. <!-- 资源类型 -->
  7. <res-type>javax.sql.DataSource</res-type>
  8. <!-- 管理权限 -->
  9. <res-auth>Container</res-auth>
  10. </resource-ref>

说明:

description :描述 (可随便写)
res-ref-name :  java:/comp/env 下面的相关的名字
res-type  :   资源的类型,资源管理器连接工厂的全限定名称。
res-auth  :   资源需要的权限管理。 分两种:Application或 container

红色字体必须与java文件中的相一致

4)Tomcat的conf/server.xml中配置虚拟目录时配置 

在配置虚拟目录时,也就是在配置conf下面的server.xml时,在context标签内添加池配置.

tomcat\conf下server.xml中找到



在其中添加:<Context path="/website" docBase="F:/JAVA/String/shujuyuan" reloadable="true">

如图:



注意:

docBase要改成你的项目目录。

path为虚拟路径,访问时的路径,注意:一定要加“/”

 

配置虚拟目录

context 节点下配置

  1. <Resource
  2. name="jdbc/mysql"
  3. author="Container"
  4. type="javax.sql.DataSource"
  5. maxActive="100"
  6. maxIdle="30"
  7. maxWait="10000"
  8. username="root"
  9. password="liukunlun"
  10. driverClassName="com.mysql.jdbc.Driver"
  11. url="jdbc:mysql://loaclhost:3306/fuxi" />

如图:



配置好后只需重启服务器,无需在web.xml文件中配置 。

 

参数设置:

 name 表示指定的jdbc,jndi名称 ,通常采用jdbc/**方式

 auth 管理权限,指定管理Resource的Manager,可以是Container或application(俩者固定使用)   

 type 指出Resource所属的类名,是什么类型的数据源,使用标准的javax.sql.DataSource

 maxActive  默认值是 8, 连接池中同时可以分派的最大活跃连接数,设为0表示无限制 

 maxIdle 连接池中最多可空闲的连接数  默认是 8

 maxWait 为连接最大的等待时间,单位毫秒,如果超过此时间将接到异常。设为-1表示无限制

 username  表示数据库用户名

 password  表示数据库用户的密码

 driverClassName  数据库驱动

 url 数据库连接url 

 testWhileIdle : 默认值是 false, 当连接池中的空闲连接是否有效

 <!-- (红色字体为常用参数设置)-->

 logAbandoned 表示被丢弃的数据库连接是否做记录,以便跟踪

 removeAbandonedTimeout : 默认值是 300( ), 活动连接的最大空闲时间

 removeAbandoned : 默认值是 false, 是否清理 removeAbandonedTimeout 秒没有使用的活动连 , 清理后并没有放回连接池  

 logAbandoned : 默认值 false, 连接池收回空闲的活动连接时是否打印消息

 testOnBorrow : 默认值是 true ,当从连接池取连接时,验证这个连接是否有效

 testOnReturn : 默认值是 flase, 当从把该连接放回到连接池的时,验证这个连接是否有效

 timeBetweenEvictionRunsMilis : 默认值是 -1 ,单位是毫秒,每隔一段多少毫秒跑一次回收空闲线程的线程

 minEvictableIdleTimeMilis : 默认值是 1000 * 60 * 30(30 分钟 ) ,单位毫秒,连接池中连接可空闲的时间

 numTestsPerEvictionRun : 默认值是 3 ,每次验证空闲连接的连接数目

 connectionInitSqls : 默认值是 null, 一组用来初始化连接的 sql 语句,这些语句只在连接工厂创建连接时执行一次。

 validationQuery : 一条 sql 语句,用来验证数据库连接是否正常。这条语句必须是一个查询模式,并至少返回一条数据。一般用“ select 1 ”

 initialSize : 默认值是 0, 连接池创建连接的初始连接数目

 minIdle : 默认是 0, 连接数中最小空闲连接数

注意

minEvictableIdleTimeMilis和removeAbandonedTimeout参数,这两个参数针对的连接对象不一样,

minEvictableIdleTimeMillis 针对连接池中的连接对象 ,

removeAbandonedTimeout 针对未被 close 的活动连接 (被调用,不在池中的连接对象 )

WEB工程中的使用

创建数据源

正确的配置后,就可以在程序中以JNDI的方式创建数据源,得到数据库连接并进行相应的操作。代码如下:

DataSourceManager类

  1. package utils;
  2. import java.sql.Connection;
  3. import javax.naming.Context;
  4. import javax.naming.InitialContext;
  5. import javax.naming.NamingException;
  6. import javax.sql.DataSource;
  7. public class DataSourceManager {
  8. private static Context context;
  9. private static DataSource dataSource;
  10. static {
  11. try {
  12. // 实例上下文目录
  13. context = new InitialContext();
  14. // 在命名空间和目录空间中查找 数据源名称 返回数据库连接池对象 JNDI
  15. dataSource=(DataSource)context.lookup("java:comp/env/jdbc/mysql");
  16. } catch (NamingException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. public static Connection getConnection() {
  21. Connection conn = null;
  22. try {
  23. conn = dataSource.getConnection();
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. }
  27. return conn;
  28. }
  29. }



JSP中使用

  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  3. <%@page import="java.sql.*, javax.sql.*, javax.naming.*"%>
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>数据</title>
  8. </head>
  9. <body>
  10. <h1>Using a DataSource</h1>
  11. <%
  12. DataSource ds = null;
  13. Connection conn = null;
  14. ResultSet result = null;
  15. Statement stmt = null;
  16. ResultSetMetaData rsmd = null;
  17. try{
  18. Context context = new InitialContext();
  19. Context envCtx = (Context)
  20. context.lookup("java:comp/env");
  21. ds = (DataSource)envCtx.lookup("jdbc/mysql");
  22. if (ds != null) {
  23. conn = ds.getConnection();
  24. stmt = conn.createStatement();
  25. result = stmt.executeQuery("SELECT * FROM student");
  26. }
  27. }
  28. catch (Exception e) {
  29. System.out.println("Error occurred " + e);
  30. }
  31. int columns=0;
  32. try {
  33. rsmd = result.getMetaData();
  34. columns = rsmd.getColumnCount();
  35. }
  36. catch (Exception e) {
  37. System.out.println("Error occurred " + e);
  38. }
  39. System.out.println(columns);
  40. %>
  41. <table width="90%" border="1">
  42. <tr>
  43. <% // write out the header cells containing the column labels
  44. try {
  45. for (int i=1; i<=columns; i++) {
  46. out.write("<th>" + rsmd.getColumnLabel(i) "</th>");
  47. }
  48. %>
  49. </tr>
  50. <%
  51. // now write out one row for each entry in the database table
  52. while (result.next()) {
  53. out.write("<tr>");
  54. for (int i=1; i<=columns; i++) {
  55. out.write("<td>" + result.getString(i) + "</td>");
  56. }
  57. out.write("</tr>");
  58. }
  59. // close the connection, resultset, and the statement
  60. result.close();
  61. stmt.close();
  62. conn.close(); // 将连接重新放回到池中
  63. } catch (Exception e) { // end of the try block
  64. System.out.println("Error " + e);
  65. }finally { // ensure everything is closed
  66. try {
  67. if (stmt != null)
  68. stmt.close();
  69. } catch (Exception e) {}
  70. try {
  71. if (conn != null)
  72. conn.close();
  73. } catch (Exception e) {}
  74. }
  75. %>
  76. </table>
  77. </body>
  78. </html>


Dao类中的使用



DBCP 数据连接池的配置和使用

DBCP(DataBase connection pool),数据库连接池。是 apache上的一个Java 连接池项目,也是 tomcat使用的连接池组件。

单独使用dbcp需要3个包:common-dbcp.jar,common-pool.jar,common-collections.jar

由于建立数据库连接是一个非常耗时耗资源的行为,所以通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,用

完后再放回去。

 

获取数据库连接的类:DBCP.java

  1. import java.sql.Connection;
  2. import javax.sql.DataSource;
  3. import org.apache.commons.dbcp2.BasicDataSource;
  4. public class DBCP {
  5. private static BasicDataSource basicDataSource = null ;
  6. private static DataSource dataSource = null;
  7. static{
  8. basicDataSource = new BasicDataSource();
  9. basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
  10. basicDataSource.setUrl("jdbc:mysql://localhost:3306/fuxi");
  11. basicDataSource.setUsername("root");
  12. basicDataSource.setPassword("liukunlun");
  13. basicDataSource.setLogAbandoned(true);
  14. basicDataSource.setMaxIdle(30);
  15. basicDataSource.setInitialSize(50);
  16. dataSource = basicDataSource;
  17. }
  18. public static Connection getConnection() {
  19. Connection conn = null;
  20. try {
  21. conn = dataSource.getConnection();
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. }
  25. return conn;
  26. }
  27. }

配置文件的 DBCO连接池的配置

连接数据库信息的配置文件:dbcp.properties

dbcp.driverClassName=com.mysql.jdbc.Driver
dbcp.url=jdbc:mysql://localhost:3306/fuxi
dbcp.username=root
dbcp.password=liukunlun
dbcp.initialSize=30  
dbcp.minIdle=10 
dbcp.maxIdle=10  
dbcp.maxWait=1000 
dbcp.maxActive=30 

获取数据库连接池的类

  1. import java.io.FileInputStream;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.sql.Connection;
  5. import java.sql.SQLException;
  6. import java.util.Properties;
  7. import javax.sql.DataSource;
  8. import org.apache.commons.dbcp.BasicDataSource;
  9. public class DbcpConnection {
  10. private static DataSource dataSource;
  11. private static Connection connection;
  12. public static void initDataSource(){
  13. FileInputStream is = null;
  14. Properties properties = new Properties();
  15. String driverClassName = null;
  16. String url = null;
  17. String username = null;
  18. String password = null;
  19. int initialSize = 0;
  20. int minIdle = 0;
  21. int maxIdle = 0;
  22. int maxWait = 0;
  23. int maxActive = 0;
  24. try {
  25. String path = System.getProperty("user.dir")+"\\src\\com\\xiami\\db\\connection\\";
  26. is = new FileInputStream(path+"dbcp.properties");
  27. properties.load(is);
  28. driverClassName = properties.getProperty("dbcp.driverClassName");
  29. url = properties.getProperty("dbcp.url");
  30. username = properties.getProperty("dbcp.username");
  31. password = properties.getProperty("dbcp.password");
  32. initialSize = Integer.parseInt((properties.getProperty("dbcp.initialSize").trim()));
  33. minIdle = Integer.parseInt((properties.getProperty("dbcp.minIdle")).trim());
  34. maxIdle = Integer.parseInt((properties.getProperty("dbcp.maxIdle")).trim());
  35. maxWait = Integer.parseInt((properties.getProperty("dbcp.maxWait")).trim());
  36. maxActive = Integer.parseInt((properties.getProperty("dbcp.maxActive")).trim());
  37. } catch (FileNotFoundException e) {
  38. e.printStackTrace();
  39. } catch (IOException ioe){
  40. ioe.printStackTrace();
  41. }finally{
  42. try {
  43. is.close();
  44. } catch (IOException e) {
  45. // TODO Auto-generated catch block
  46. e.printStackTrace();
  47. }
  48. }
  49. BasicDataSource bds = new BasicDataSource();
  50. bds.setUrl(url);
  51. bds.setDriverClassName(driverClassName);
  52. bds.setUsername(username);
  53. bds.setPassword(password);
  54. bds.setInitialSize(initialSize);
  55. bds.setMaxActive(maxActive);
  56. bds.setMinIdle(minIdle);
  57. bds.setMaxIdle(maxIdle);
  58. bds.setMaxWait(maxWait);
  59. dataSource = bds;
  60. }
  61. public static Connection getConnection() throws SQLException {
  62. if (dataSource == null) {
  63. initDataSource();
  64. }
  65. Connection conn = null;
  66. if (dataSource != null) {
  67. conn = dataSource.getConnection();
  68. }
  69. return conn;
  70. }
  71. }


Service层使用的时候:ZhiDianJieDu.java (业务逻辑处理的类)

  1. package utils;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.ResultSetMetaData;
  5. import java.sql.Statement;
  6. public class Duquxinxi{
  7. private Statement stmt = null;
  8. private ResultSet result = null;
  9. private ResultSetMetaData rsmd = null;
  10. private Connection conn = null;
  11. public void test() {
  12. try {
  13. conn = DBCP.getConnection();
  14. System.out.println("连接成功!");
  15. stmt = conn.createStatement();
  16. result = stmt.executeQuery("SELECT * FROM fuxi");
  17. } catch (Exception e) {
  18. System.out.println(e);
  19. }
  20. int columns = 0;
  21. try {
  22. rsmd = result.getMetaData();
  23. columns = rsmd.getColumnCount();
  24. } catch (Exception e) {
  25. System.out.println("Error occurred " + e);
  26. }
  27. try {
  28. for (int i = 1; i <= columns; i++) {
  29. System.out.println(rsmd.getColumnLabel(i));
  30. }
  31. while (result.next()) {
  32. for (int i = 1; i <= columns; i++) {
  33. System.out.println(result.getString(i));
  34. }
  35. System.out.println();
  36. }
  37. // close the connection, resultset, and the statement
  38. // 关闭连接,resultset,声明
  39. result.close();
  40. stmt.close();
  41. conn.close();
  42. } // end of the try block
  43. catch (Exception e) {
  44. System.out.println("Error " + e);
  45. }
  46. // ensure everything is closed 确保一切都是封闭的
  47. finally {
  48. try {
  49. if (stmt != null)
  50. stmt.close();
  51. } catch (Exception e) {
  52. }
  53. try {
  54. if (conn != null)
  55. conn.close();
  56. } catch (Exception e) {
  57. }
  58. }
  59. }
  60. }

C3P0 数据库连接池的配置和使用

C3p0.properties 位置



内容

#jdbc基本信息  
driverClass=org.gjt.mm.mysql.Driver  
jdbcUrl=jdbc:mysql://localhost:3306/fuxi  
user=root
password=liukunlun
  
#c3p0连接池信息  
c3p0.minPoolSize=3  
c3p0.maxPoolSize=25  
  
#当连接池中的连接耗尽的时候c3p0一次同时获取的连接数  
c3p0.acquireIncrement=3  
#定义在从数据库获取新连接失败后重复尝试的次数  
c3p0.acquireRetryAttempts=60  
#两次连接中间隔时间,单位毫秒  
c3p0.acquireRetryDelay=1000  
#连接关闭时默认将所有未提交的操作回滚  
c3p0.autoCommitOnClose=false  
#当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出#SQLException,如设为0则无限期等待。单位毫秒  
c3p0.checkoutTimeout=3000  
#每120秒检查所有连接池中的空闲连接。Default0  
c3p0.idleConnectionTestPeriod=120  
#最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default0  
c3p0.maxIdleTime=600  
#如果设为true那么在取得连接的同时将校验连接的有效性。Defaultfalse  
c3p0.testConnectionOnCheckin=true  
#c3p0将建一张名为c3p0TestTable的空表,并使用其自带的查询语句进行测试。  
jdbc.automaticTestTable = c3p0TestTable 

C3P0ConnentionProvider.Java

  1. package utils;
  2. import java.io.FileInputStream;
  3. import java.sql.Connection;
  4. import java.sql.SQLException;
  5. import java.util.Properties;
  6. import javax.sql.DataSource;
  7. import com.mchange.v2.c3p0.DataSources;
  8. /**
  9. * c3p0连接池管理类
  10. */
  11. public class C3P0ConnentionProvider {
  12. private static final String JDBC_DRIVER = "driverClass";
  13. private static final String JDBC_URL = "jdbcUrl";
  14. private static DataSource ds;
  15. /**
  16. * 初始化连接池代码块
  17. */
  18. static {
  19. initDBSource();
  20. }
  21. /**
  22. * 初始化c3p0连接池
  23. */
  24. private static final void initDBSource() {
  25. Properties c3p0Pro = new Properties();
  26. try {
  27. // 加载配置文件
  28. String path = C3P0ConnentionProvider.class.getResource("/").getPath();
  29. String websiteURL = (path.replace("/build/classes", "").replace("%20"," ").replace("classes/", "") + "c3p0.properties").replaceFirst("/", "");
  30. FileInputStream in = new FileInputStream(websiteURL);
  31. c3p0Pro.load(in);
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. String drverClass = c3p0Pro.getProperty(JDBC_DRIVER);
  36. if (drverClass != null) {
  37. try {
  38. // 加载驱动类
  39. Class.forName(drverClass);
  40. } catch (ClassNotFoundException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. Properties jdbcpropes = new Properties();
  45. Properties c3propes = new Properties();
  46. for (Object key : c3p0Pro.keySet()) {
  47. String skey = (String) key;
  48. if (skey.startsWith("c3p0.")) {
  49. c3propes.put(skey, c3p0Pro.getProperty(skey));
  50. } else {
  51. jdbcpropes.put(skey, c3p0Pro.getProperty(skey));
  52. }
  53. }
  54. try {
  55. // 建立连接池
  56. DataSource unPooled = DataSources.unpooledDataSource(c3p0Pro.getProperty(JDBC_URL), jdbcpropes);
  57. ds = DataSources.pooledDataSource(unPooled, c3propes);
  58. } catch (SQLException e) {
  59. e.printStackTrace();
  60. }
  61. }
  62. /**
  63. * 获取数据库连接对象
  64. *
  65. * @return 数据连接对象
  66. * @throws SQLException
  67. */
  68. public static synchronized Connection getConnection() throws SQLException {
  69. final Connection conn = ds.getConnection();
  70. conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
  71. return conn;
  72. }
  73. }

使用

datasource2.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <%@page import="utils.*"%>
  5. <%@page import="java.sql.*, javax.sql.*, javax.naming.*"%>
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title>Insert title here</title>
  10. </head>
  11. <body>
  12. <%
  13. Statement stmt = null;
  14. ResultSet result = null;
  15. ResultSetMetaData rsmd = null;
  16. Connection conn = null;
  17. try{
  18. conn = C3P0ConnentionProvider.getConnection();
  19. //conn = DataSourceManager.getConnection();
  20. out.println("连接成功!");
  21. stmt = conn.createStatement();
  22. result = stmt.executeQuery("SELECT * FROM fuxi");
  23. } catch (Exception e) {
  24. out.println(e);
  25. }
  26. int columns=0;
  27. try {
  28. rsmd = result.getMetaData();
  29. columns = rsmd.getColumnCount();
  30. }
  31. catch (Exception e) {
  32. System.out.println("Error occurred " + e);
  33. }
  34. %>
  35. <table width="90%" border="1">
  36. <tr>
  37. <% // write out the header cells containing the column labels 写出标题单元格包含列标签
  38. try {
  39. for (int i=1; i<=columns; i++) {
  40. out.write("<th>" + rsmd.getColumnLabel(i) + "</th>");
  41. }
  42. %>
  43. </tr>
  44. <% // now write out one row for each entry in the database table 现在写出一行中的每个条目数据库表中
  45. while (result.next()) {
  46. out.write("<tr>");
  47. for (int i=1; i<=columns; i++) {
  48. out.write("<td>" + result.getString(i) + "</td>");
  49. }
  50. out.write("</tr>");
  51. }
  52. // close the connection, resultset, and the statement 关闭连接,resultset,声明
  53. result.close();
  54. stmt.close();
  55. //conn.close();
  56. } // end of the try block
  57. catch (Exception e) {
  58. System.out.println("Error " + e);
  59. }
  60. // ensure everything is closed 确保一切都是封闭的
  61. finally {
  62. try {
  63. if (stmt != null)
  64. stmt.close();
  65. } catch (Exception e) {}
  66. try {
  67. // if (conn != null)
  68. // conn.close();
  69. } catch (Exception e) {}
  70. }
  71. %>
  72. </table>
  73. </body>
  74. </html>


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/976481
推荐阅读
相关标签
  

闽ICP备14008679号