zoukankan      html  css  js  c++  java
  • 【转】java数据库操作

    本文来自:曹胜欢博客专栏。转载请注明出处:http://blog.csdn.net/csh624366188

       数据库访问几乎每一个稍微成型的程序都要用到的知识,怎么高效的访问数据库也是我们学习的一个重点,今天的任务就是总结java访问数据库的方法和有关API,java访问数据库主要用的方法是JDBC,它是java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法,下面我们就具体来总结一下JDBC

    一:Java访问数据库的具体步骤:

    1 加载(注册)数据库 

     驱动加载就是把各个数据库提供的访问数据库的API加载到我们程序进来,加载JDBC驱动,并将其注册到DriverManager中,每一种数据库提供的数据库驱动不一样,加载驱动时要把jar包添加到lib文件夹下,下面看一下一些主流数据库的JDBC驱动加裁注册的代码: 

    //Oracle8/8i/9iO数据库(thin模式) 

    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); 

    //Sql Server7.0/2000数据库   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); 

    //Sql Server2005/2008数据库   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 

    //DB2数据库 

    Class.froName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();  

    //MySQL数据库  Class.forName("com.mysql.jdbc.Driver").newInstance(); 

    建立链接   

    建立数据库之间的连接是访问数据库的必要条件,就像南水北调调水一样,要想调水首先由把沟通的河流打通。建立连接对于不同数据库也是不一样的,下面看一下一些主流数据库建立数据库连接,取得Connection对象的不同方式:

     //Oracle8/8i/9i数据库(thin模式) 

      String url="jdbc:oracle:thin:@localhost:1521:orcl"; 

      String user="scott"; 

      String password="tiger"; 

      Connection conn=DriverManager.getConnection(url,user,password); 

      

      //Sql Server7.0/2000/2005/2008数据库 

      String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"; 

      String user="sa"; 

      String password=""; 

      Connection conn=DriverManager.getConnection(url,user,password); 

      

      //DB2数据库 

      String url="jdbc:db2://localhost:5000/sample"; 

      String user="amdin" 

      String password=-""; 

      Connection conn=DriverManager.getConnection(url,user,password); 

      

    //MySQL数据库 

    String url="jdbc:mysql://localhost:3306/testDB?user=root&password=root&useUnicode=true&characterEncoding=gb2312"; 

    Connection conn=DriverManager.getConnection(url); 

    3. 执行SQL语句  

    数据库连接建立好之后,接下来就是一些准备工作和执行sql语句了,准备工作要做的就是建立Statement对象PreparedStatement对象,例如:

     //建立Statement对象 

     Statement stmt=conn.createStatement(); 

     //建立PreparedStatement对象 

     String sql="select * from user where userName=? and password=?"; 

      PreparedStatement pstmt=Conn.prepareStatement(sql); 

      pstmt.setString(1,"admin"); 

      pstmt.setString(2,"liubin"); 

    做好准备工作之后就可以执行sql语句了,执行sql语句:

    String sql="select * from users"; 

    ResultSet rs=stmt.executeQuery(sql); 

    //执行动态SQL查询 

    ResultSet rs=pstmt.executeQuery(); 

    //执行insert update delete等语句,先定义sql 

    stmt.executeUpdate(sql); 

    4 处理结果集  

     访问结果记录集ResultSet对象。例如: 

      while(rs.next) 

      { 

      out.println("你的第一个字段内容为:"+rs.getString("Name")); 

      out.println("你的第二个字段内容为:"+rs.getString(2)); 

      } 

    5 关闭数据库 

     依次将ResultSet、Statement、PreparedStatement、Connection对象关     闭,释放所占用的资源.例如: 

      rs.close(); 

      stmt.clost(); 

      pstmt.close(); 

      con.close(); 

    二:JDBC事务

    什么是事务:

    首先,说说什么事务。我认为事务,就是一组操作数据库的动作集合。

    事务是现代数据库理论中的核心概念之一。如果一组处理步骤或者全部发生或者一步也不执行,我们称该组处理步骤为一个事务。当所有的步骤像一个操 作一样被完整地执行,我们称该事务被提交。由于其中的一部分或多步执行失败,导致没有步骤被提交,则事务必须回滚到最初的系统状态。

    事务必须服从ISO/IEC所制定的ACID原则。ACID是原子性(atomicity)、一致性(consistency)、隔离性 (isolation)和持久性(durability)的缩写。事务的原子性表示事务执行过程中的任何失败都将导致事务所做的任何修改失效。一致性表示 当事务执行失败时,所有被该事务影响的数据都应该恢复到事务执行前的状态。隔离性表示在事务执行过程中对数据的修改,在事务提交之前对其他事务不可见。持 久性表示当系统或介质发生故障时,确保已提交事务的更新不能丢失。持久性通过数据库备份和恢复来保证。

    JDBC 事务是用 Connection 对象控制的。JDBC Connection 接口( java.sql.Connection )提供了两种事务模式:自动提交和手工提交。 java.sql.Connection 提供了以下控制事务的方法: 
    public void setAutoCommit(boolean) 
    public boolean getAutoCommit() 
    public void commit() 
    public void rollback() 
    使用 JDBC 事务界定时,您可以将多个 SQL 语句结合到一个事务中。JDBC 事务的一个缺点是事务的范围局限于一个数据库连接。一个 JDBC 事务不能跨越多个数据库。

    三:java操作数据库连接池

    在总结java操作数据库连接池发现一篇很好的文章,所以就不做具体总结了,直接上地址:

    http://www.blogjava.net/chunkyo/archive/2007/01/16/94266.html

    最后附一段比较经典的代码吧:

    1. import java.sql.Connection;  
    2. import java.sql.DatabaseMetaData;  
    3. import java.sql.Driver;  
    4. import java.sql.DriverManager;  
    5. import java.sql.SQLException;  
    6. import java.sql.Statement;  
    7. import java.util.Enumeration;  
    8. import java.util.Vector;  
    9. public class ConnectionPool {  
    10. private String jdbcDriver = ""; // 数据库驱动  
    11. private String dbUrl = ""; // 数据 URL  
    12. private String dbUsername = ""; // 数据库用户名  
    13. private String dbPassword = ""; // 数据库用户密码  
    14. private String testTable = ""; // 测试连接是否可用的测试表名,默认没有测试表  
    15. private int initialConnections = 10; // 连接池的初始大小  
    16. private int incrementalConnections = 5;// 连接池自动增加的大小  
    17. private int maxConnections = 50; // 连接池最大的大小  
    18. private Vector connections = null; // 存放连接池中数据库连接的向量 , 初始时为 null  
    19.   
    20. // 它中存放的对象为 PooledConnection 型  
    21.   
    22. /** 
    23. * 构造函数 
    24. * @param jdbcDriver String JDBC 驱动类串 
    25. * @param dbUrl String 数据库 URL 
    26. * @param dbUsername String 连接数据库用户名 
    27. * @param dbPassword String 连接数据库用户的密码 
    28. */  
    29.   
    30. public ConnectionPool(String jdbcDriver,String dbUrl,String dbUsername,String dbPassword) {  
    31.          this.jdbcDriver = jdbcDriver;  
    32.          this.dbUrl = dbUrl;  
    33.          this.dbUsername = dbUsername;   
    34.          this.dbPassword = dbPassword;  
    35. }  
    36.   
    37. /** 
    38.  
    39. * 返回连接池的初始大小 
    40. * @return 初始连接池中可获得的连接数量 
    41. */  
    42. public int getInitialConnections() {  
    43.   
    44.          return this.initialConnections;  
    45. }  
    46.   
    47. /** 
    48.  
    49. * 设置连接池的初始大小 
    50.  
    51.  
    52. * @param 用于设置初始连接池中连接的数量 
    53.  
    54. */  
    55.   
    56. public void setInitialConnections(int initialConnections) {  
    57.          this.initialConnections = initialConnections;  
    58. }  
    59.   
    60. /** 
    61.  
    62. * 返回连接池自动增加的大小 、 
    63. * @return 连接池自动增加的大小 
    64. */  
    65. public int getIncrementalConnections() {  
    66.   
    67.          return this.incrementalConnections;  
    68.   
    69. }  
    70.   
    71. /** 
    72. * 设置连接池自动增加的大小 
    73. * @param 连接池自动增加的大小 
    74. */  
    75.   
    76. public void setIncrementalConnections(int incrementalConnections) {  
    77.   
    78.          this.incrementalConnections = incrementalConnections;  
    79.   
    80. }  
    81.   
    82. /** 
    83. * 返回连接池中最大的可用连接数量 
    84. * @return 连接池中最大的可用连接数量 
    85. */  
    86.   
    87. public int getMaxConnections() {  
    88.          return this.maxConnections;  
    89. }  
    90.   
    91. /** 
    92.  
    93. * 设置连接池中最大可用的连接数量 
    94.  
    95.  
    96. * @param 设置连接池中最大可用的连接数量值 
    97.  
    98. */  
    99.   
    100. public void setMaxConnections(int maxConnections) {  
    101.   
    102.          this.maxConnections = maxConnections;  
    103.   
    104. }  
    105.   
    106. /** 
    107.  
    108. * 获取测试数据库表的名字 
    109. * @return 测试数据库表的名字 
    110. */  
    111. public String getTestTable() {  
    112.   
    113.          return this.testTable;  
    114.   
    115. }  
    116.   
    117. /** 
    118. * 设置测试表的名字 
    119. * @param testTable String 测试表的名字 
    120. */  
    121. public void setTestTable(String testTable) {  
    122.          this.testTable = testTable;  
    123. }  
    124.   
    125. /** 
    126.  
    127. * 创建一个数据库连接池,连接池中的可用连接的数量采用类成员 
    128. * initialConnections 中设置的值 
    129. */  
    130. public synchronized void createPool() throws Exception {  
    131.   
    132.          // 确保连接池没有创建  
    133.     
    134.          // 如果连接池己经创建了,保存连接的向量 connections 不会为空  
    135.     
    136.          if (connections != null) {  
    137.     
    138.           return; // 如果己经创建,则返回  
    139.     
    140.          }  
    141.     
    142.          // 实例化 JDBC Driver 中指定的驱动类实例  
    143.     
    144.          Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance());  
    145.     
    146.          DriverManager.registerDriver(driver); // 注册 JDBC 驱动程序  
    147.     
    148.          // 创建保存连接的向量 , 初始时有 0 个元素  
    149.     
    150.          connections = new Vector();  
    151.     
    152.          // 根据 initialConnections 中设置的值,创建连接。  
    153.     
    154.          createConnections(this.initialConnections);  
    155.     
    156.          System.out.println(" 数据库连接池创建成功! ");  
    157.   
    158. }  
    159.   
    160. /** 
    161.  
    162. * 创建由 numConnections 指定数目的数据库连接 , 并把这些连接 
    163.  
    164. * 放入 connections 向量中 
    165. * @param numConnections 要创建的数据库连接的数目 
    166. */  
    167. @SuppressWarnings("unchecked")  
    168. private void createConnections(int numConnections) throws SQLException {  
    169.   
    170.          // 循环创建指定数目的数据库连接  
    171.     
    172.          for (int x = 0; x < numConnections; x++) {  
    173.     
    174.           // 是否连接池中的数据库连接的数量己经达到最大?最大值由类成员 maxConnections  
    175.      
    176.           // 指出,如果 maxConnections 为 0 或负数,表示连接数量没有限制。  
    177.      
    178.           // 如果连接数己经达到最大,即退出。  
    179.      
    180.           if (this.maxConnections > 0 && this.connections.size() >= this.maxConnections) {  
    181.      
    182.            break;  
    183.      
    184.           }  
    185.     
    186.           //add a new PooledConnection object to connections vector  
    187.      
    188.           // 增加一个连接到连接池中(向量 connections 中)  
    189.      
    190.           try{  
    191.      
    192.            connections.addElement(new PooledConnection(newConnection()));  
    193.      
    194.           }catch(SQLException e){  
    195.      
    196.            System.out.println(" 创建数据库连接失败! "+e.getMessage());  
    197.      
    198.           throw new SQLException();  
    199.      
    200.           }  
    201.      
    202.           System.out.println(" 数据库连接己创建 ......");  
    203.      
    204.          }  
    205. }  
    206.   
    207. /** 
    208.  
    209. * 创建一个新的数据库连接并返回它 
    210. * @return 返回一个新创建的数据库连接 
    211. */  
    212. private Connection newConnection() throws SQLException {  
    213.   
    214.          // 创建一个数据库连接  
    215.     
    216.          Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);  
    217.     
    218.          // 如果这是第一次创建数据库连接,即检查数据库,获得此数据库允许支持的  
    219.     
    220.          // 最大客户连接数目  
    221.     
    222.          //connections.size()==0 表示目前没有连接己被创建  
    223.     
    224.          if (connections.size() == 0) {  
    225.     
    226.           DatabaseMetaData metaData = conn.getMetaData();  
    227.      
    228.           int driverMaxConnections = metaData.getMaxConnections();  
    229.      
    230.           // 数据库返回的 driverMaxConnections 若为 0 ,表示此数据库没有最大  
    231.      
    232.           // 连接限制,或数据库的最大连接限制不知道  
    233.      
    234.           //driverMaxConnections 为返回的一个整数,表示此数据库允许客户连接的数目  
    235.      
    236.           // 如果连接池中设置的最大连接数量大于数据库允许的连接数目 , 则置连接池的最大  
    237.      
    238.           // 连接数目为数据库允许的最大数目  
    239.      
    240.           if (driverMaxConnections > 0 && this.maxConnections > driverMaxConnections) {  
    241.      
    242.            this.maxConnections = driverMaxConnections;  
    243.      
    244.           }  
    245.          }   
    246.          return conn; // 返回创建的新的数据库连接  
    247.   
    248. }  
    249.   
    250. /** 
    251.  
    252. * 通过调用 getFreeConnection() 函数返回一个可用的数据库连接 , 
    253.  
    254. * 如果当前没有可用的数据库连接,并且更多的数据库连接不能创 
    255.  
    256. * 建(如连接池大小的限制),此函数等待一会再尝试获取。 
    257.  
    258.  
    259. * @return 返回一个可用的数据库连接对象 
    260.  
    261. */  
    262.   
    263. public synchronized Connection getConnection() throws SQLException {  
    264.   
    265.          // 确保连接池己被创建  
    266.     
    267.          if (connections == null) {  
    268.     
    269.           return null; // 连接池还没创建,则返回 null  
    270.     
    271.          }  
    272.     
    273.          Connection conn = getFreeConnection(); // 获得一个可用的数据库连接  
    274.     
    275.          // 如果目前没有可以使用的连接,即所有的连接都在使用中  
    276.     
    277.          while (conn == null){  
    278.     
    279.           // 等一会再试  
    280.      
    281.           wait(250);  
    282.      
    283.           conn = getFreeConnection(); // 重新再试,直到获得可用的连接,如果  
    284.      
    285.           //getFreeConnection() 返回的为 null  
    286.      
    287.           // 则表明创建一批连接后也不可获得可用连接  
    288.     
    289.          }  
    290.     
    291.          return conn;// 返回获得的可用的连接  
    292. }  
    293.   
    294. /** 
    295.  
    296. * 本函数从连接池向量 connections 中返回一个可用的的数据库连接,如果 
    297.  
    298. * 当前没有可用的数据库连接,本函数则根据 incrementalConnections 设置 
    299.  
    300. * 的值创建几个数据库连接,并放入连接池中。 
    301.  
    302. * 如果创建后,所有的连接仍都在使用中,则返回 null 
    303.  
    304. * @return 返回一个可用的数据库连接 
    305.  
    306. */  
    307.   
    308. private Connection getFreeConnection() throws SQLException {  
    309.   
    310.          // 从连接池中获得一个可用的数据库连接  
    311.     
    312.          Connection conn = findFreeConnection();  
    313.     
    314.          if (conn == null) {  
    315.     
    316.           // 如果目前连接池中没有可用的连接  
    317.      
    318.           // 创建一些连接  
    319.      
    320.           createConnections(incrementalConnections);  
    321.      
    322.           // 重新从池中查找是否有可用连接  
    323.      
    324.           conn = findFreeConnection();  
    325.      
    326.           if (conn == null) {  
    327.      
    328.            // 如果创建连接后仍获得不到可用的连接,则返回 null  
    329.       
    330.            return null;  
    331.      
    332.           }  
    333.     
    334.          }  
    335.     
    336.          return conn;  
    337.   
    338. }  
    339.   
    340. /** 
    341.  
    342. * 查找连接池中所有的连接,查找一个可用的数据库连接, 
    343.  
    344. * 如果没有可用的连接,返回 null 
    345.  
    346.  
    347. * @return 返回一个可用的数据库连接 
    348.  
    349. */  
    350.   
    351. private Connection findFreeConnection() throws SQLException {  
    352.   
    353.          Connection conn = null;  
    354.     
    355.          PooledConnection pConn = null;  
    356.     
    357.          // 获得连接池向量中所有的对象  
    358.     
    359.          Enumeration enumerate = connections.elements();  
    360.     
    361.          // 遍历所有的对象,看是否有可用的连接  
    362.     
    363.          while (enumerate.hasMoreElements()) {  
    364.     
    365.           pConn = (PooledConnection) enumerate.nextElement();  
    366.      
    367.           if (!pConn.isBusy()) {  
    368.      
    369.            // 如果此对象不忙,则获得它的数据库连接并把它设为忙  
    370.       
    371.            conn = pConn.getConnection();  
    372.       
    373.            pConn.setBusy(true);  
    374.       
    375.            // 测试此连接是否可用  
    376.       
    377.            if (!testConnection(conn)) {  
    378.       
    379.             // 如果此连接不可再用了,则创建一个新的连接,  
    380.        
    381.             // 并替换此不可用的连接对象,如果创建失败,返回 null  
    382.        
    383.             try{  
    384.        
    385.              conn = newConnection();  
    386.        
    387.             }catch(SQLException e){  
    388.        
    389.              System.out.println(" 创建数据库连接失败! "+e.getMessage());  
    390.        
    391.              return null;  
    392.        
    393.             }  
    394.       
    395.             pConn.setConnection(conn);  
    396.       
    397.            }  
    398.       
    399.            break; // 己经找到一个可用的连接,退出  
    400.      
    401.           }  
    402.     
    403.          }  
    404.     
    405.          return conn;// 返回找到到的可用连接  
    406.   
    407. }  
    408.   
    409. /** 
    410.  
    411. * 测试一个连接是否可用,如果不可用,关掉它并返回 false 
    412.  
    413. * 否则可用返回 true 
    414.  
    415.  
    416. * @param conn 需要测试的数据库连接 
    417.  
    418. * @return 返回 true 表示此连接可用, false 表示不可用 
    419.  
    420. */  
    421.   
    422. private boolean testConnection(Connection conn) {  
    423.   
    424.          try {  
    425.     
    426.           // 判断测试表是否存在  
    427.      
    428.           if (testTable.equals("")) {  
    429.      
    430.            // 如果测试表为空,试着使用此连接的 setAutoCommit() 方法  
    431.       
    432.            // 来判断连接否可用(此方法只在部分数据库可用,如果不可用 ,  
    433.       
    434.            // 抛出异常)。注意:使用测试表的方法更可靠  
    435.       
    436.            conn.setAutoCommit(true);  
    437.      
    438.           } else {// 有测试表的时候使用测试表测试  
    439.      
    440.            //check if this connection is valid  
    441.       
    442.            Statement stmt = conn.createStatement();  
    443.       
    444.            stmt.execute("select count(*) from " + testTable);  
    445.      
    446.           }  
    447.     
    448.          } catch (SQLException e) {  
    449.     
    450.           // 上面抛出异常,此连接己不可用,关闭它,并返回 false;  
    451.     
    452.           closeConnection(conn);  
    453.     
    454.           return false;  
    455.     
    456.          }  
    457.     
    458.          // 连接可用,返回 true  
    459.     
    460.          return true;  
    461.   
    462. }  
    463.   
    464. /** 
    465.  
    466. * 此函数返回一个数据库连接到连接池中,并把此连接置为空闲。 
    467.  
    468. * 所有使用连接池获得的数据库连接均应在不使用此连接时返回它。 
    469.  
    470.  
    471. * @param 需返回到连接池中的连接对象 
    472.  
    473. */  
    474.   
    475. public void returnConnection(Connection conn) {  
    476.   
    477.          // 确保连接池存在,如果连接没有创建(不存在),直接返回  
    478.     
    479.          if (connections == null) {  
    480.     
    481.           System.out.println(" 连接池不存在,无法返回此连接到连接池中 !");  
    482.      
    483.           return;  
    484.     
    485.          }  
    486.   
    487.          PooledConnection pConn = null;  
    488.     
    489.          Enumeration enumerate = connections.elements();  
    490.     
    491.          // 遍历连接池中的所有连接,找到这个要返回的连接对象  
    492.     
    493.          while (enumerate.hasMoreElements()) {  
    494.   
    495.           pConn = (PooledConnection) enumerate.nextElement();  
    496.      
    497.           // 先找到连接池中的要返回的连接对象  
    498.      
    499.           if (conn == pConn.getConnection()) {  
    500.      
    501.            // 找到了 , 设置此连接为空闲状态  
    502.       
    503.            pConn.setBusy(false);  
    504.       
    505.            break;  
    506.      
    507.           }  
    508.   
    509.          }  
    510.   
    511. }  
    512.   
    513. /** 
    514.  
    515. * 刷新连接池中所有的连接对象 
    516.  
    517.  
    518. */  
    519.   
    520. public synchronized void refreshConnections() throws SQLException {  
    521.   
    522.          // 确保连接池己创新存在  
    523.     
    524.          if (connections == null) {  
    525.     
    526.           System.out.println(" 连接池不存在,无法刷新 !");  
    527.     
    528.           return;  
    529.     
    530.          }  
    531.     
    532.          PooledConnection pConn = null;  
    533.     
    534.          Enumeration enumerate = connections.elements();  
    535.     
    536.          while (enumerate.hasMoreElements()) {  
    537.   
    538.           // 获得一个连接对象  
    539.      
    540.           pConn = (PooledConnection) enumerate.nextElement();  
    541.      
    542.           // 如果对象忙则等 5 秒 ,5 秒后直接刷新  
    543.      
    544.           if (pConn.isBusy()) {  
    545.      
    546.            wait(5000); // 等 5 秒  
    547.      
    548.           }  
    549.      
    550.           // 关闭此连接,用一个新的连接代替它。  
    551.      
    552.           closeConnection(pConn.getConnection());  
    553.      
    554.           pConn.setConnection(newConnection());  
    555.      
    556.           pConn.setBusy(false);  
    557.      
    558.          }  
    559.   
    560. }  
    561.   
    562. /** 
    563.  
    564. * 关闭连接池中所有的连接,并清空连接池。 
    565.  
    566. */  
    567.   
    568. public synchronized void closeConnectionPool() throws SQLException {  
    569.   
    570.          // 确保连接池存在,如果不存在,返回  
    571.     
    572.          if (connections == null) {  
    573.     
    574.           System.out.println(" 连接池不存在,无法关闭 !");  
    575.     
    576.           return;  
    577.     
    578.          }  
    579.     
    580.          PooledConnection pConn = null;  
    581.     
    582.          Enumeration enumerate = connections.elements();  
    583.     
    584.          while (enumerate.hasMoreElements()) {  
    585.     
    586.           pConn = (PooledConnection) enumerate.nextElement();  
    587.     
    588.           // 如果忙,等 5 秒  
    589.     
    590.           if (pConn.isBusy()) {  
    591.     
    592.            wait(5000); // 等 5 秒  
    593.     
    594.           }  
    595.     
    596.          //5 秒后直接关闭它  
    597.     
    598.          closeConnection(pConn.getConnection());  
    599.     
    600.          // 从连接池向量中删除它  
    601.     
    602.          connections.removeElement(pConn);  
    603.     
    604.          }  
    605.     
    606.          // 置连接池为空  
    607.     
    608.          connections = null;  
    609.   
    610. }  
    611.   
    612. /** 
    613.  
    614. * 关闭一个数据库连接 
    615.  
    616.  
    617. * @param 需要关闭的数据库连接 
    618.  
    619. */  
    620.   
    621. private void closeConnection(Connection conn) {  
    622.   
    623.          try {  
    624.     
    625.           conn.close();  
    626.     
    627.          }catch (SQLException e) {  
    628.     
    629.           System.out.println(" 关闭数据库连接出错: "+e.getMessage());  
    630.     
    631.          }  
    632.   
    633. }  
    634.   
    635. /** 
    636.  
    637. * 使程序等待给定的毫秒数 
    638.  
    639.  
    640. * @param 给定的毫秒数 
    641.  
    642. */  
    643.   
    644. private void wait(int mSeconds) {  
    645.   
    646.          try {  
    647.     
    648.           Thread.sleep(mSeconds);  
    649.     
    650.          } catch (InterruptedException e) {  
    651.     
    652.          }  
    653.   
    654. }  
    655.   
    656. /** 
    657.  
    658.  
    659. * 内部使用的用于保存连接池中连接对象的类 
    660.  
    661. * 此类中有两个成员,一个是数据库的连接,另一个是指示此连接是否 
    662.  
    663. * 正在使用的标志。 
    664.  
    665. */  
    666.   
    667. class PooledConnection {  
    668.   
    669.          Connection connection = null;// 数据库连接  
    670.     
    671.          boolean busy = false; // 此连接是否正在使用的标志,默认没有正在使用  
    672.     
    673.          // 构造函数,根据一个 Connection 构告一个 PooledConnection 对象  
    674.     
    675.          public PooledConnection(Connection connection) {  
    676.     
    677.           this.connection = connection;  
    678.     
    679.          }  
    680.     
    681.          // 返回此对象中的连接  
    682.     
    683.          public Connection getConnection() {  
    684.     
    685.           return connection;  
    686.   
    687.          }  
    688.   
    689.          // 设置此对象的,连接  
    690.     
    691.          public void setConnection(Connection connection) {  
    692.     
    693.           this.connection = connection;  
    694.      
    695.          }  
    696.      
    697.          // 获得对象连接是否忙  
    698.      
    699.          public boolean isBusy() {  
    700.      
    701.           return busy;  
    702.      
    703.          }  
    704.      
    705.          // 设置对象的连接正在忙  
    706.      
    707.          public void setBusy(boolean busy) {  
    708.      
    709.           this.busy = busy;  
    710.      
    711.          }  
    712.   
    713. }  
    714.   
    715. }  
    716.   
    717. =======================================  
    718.   
    719. 这个例子是根据POSTGRESQL数据库写的,  
    720. 请用的时候根据实际的数据库调整。  
    721.   
    722. 调用方法如下:  
    723.   
    724. ① ConnectionPool connPool  
    725.                                      = new ConnectionPool("org.postgresql.Driver"  
    726.                                                                          ,"jdbc:postgresql://dbURI:5432/DBName"  
    727.                                                                          ,"postgre"  
    728.                                                                          ,"postgre");  
    729.   
    730. ② connPool .createPool();  
    731.   Connection conn = connPool .getConnection();  



     本文来自:曹胜欢博客专栏。转载请注明出处:http://blog.csdn.net/csh624366188

  • 相关阅读:
    2021/1/10周总结一
    java基础复习五
    java基础复习四
    构建之法读书笔记三
    javaweb学生教务系统
    java基础复习三
    关于eclipse项目错误的一些小经验总结
    Java基础复习二
    JavaDoc文档
    2017-2018-2 20179216 《网络攻防与实践》 第四周总结
  • 原文地址:https://www.cnblogs.com/royalisme/p/4843509.html
Copyright © 2011-2022 走看看