鍍金池/ 教程/ Java/ Java 數(shù)據(jù)庫操作
Struts2
Java 泛型
排序算法
Java 內(nèi)存管理
Webservice
Spring
輸入輸出流
Socket
字符串與數(shù)組
面向?qū)ο缶幊?/span>
海量數(shù)據(jù)處理
Hibernate
Netty
基本類型與運算符
常見設計模式
Java 虛擬機
Java 多線程
JDBC
搭建 Java 開發(fā)環(huán)境
Java 數(shù)據(jù)庫操作
異常處理
集合類
Servlet 與 JSP

Java 數(shù)據(jù)庫操作

java 程序員從笨鳥到菜鳥之(七)—java 數(shù)據(jù)庫操作

數(shù)據(jù)庫訪問幾乎每一個稍微成型的程序都要用到的知識,怎么高效的訪問數(shù)據(jù)庫也是我們學習的一個重點,今天的任務就是總結 java 訪問數(shù)據(jù)庫的方法和有關 API,java 訪問數(shù)據(jù)庫主要用的方法是 JDBC,它是 java 語言中用來規(guī)范客戶端程序如何來訪問數(shù)據(jù)庫的應用程序接口,提供了諸如查詢和更新數(shù)據(jù)庫中數(shù)據(jù)的方法,下面我們就具體來總結一下 JDBC 一:Java 訪問數(shù)據(jù)庫的具體步驟:

  1. 加載(注冊)數(shù)據(jù)庫 驅(qū)動加載就是把各個數(shù)據(jù)庫提供的訪問數(shù)據(jù)庫的 API 加載到我們程序進來,加載 JDBC 驅(qū)動,并將其注冊到 DriverManager 中,每一種數(shù)據(jù)庫提供的數(shù)據(jù)庫驅(qū)動不一樣,加載驅(qū)動時要把 jar 包添加到 lib 文件夾下,下面看一下一些主流數(shù)據(jù)庫的 JDBC 驅(qū)動加裁注冊的代碼:
//Oracle8/8i/9iO數(shù)據(jù)庫(thin模式) 
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); 
//Sql Server7.0/2000數(shù)據(jù)庫   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); 
//Sql Server2005/2008數(shù)據(jù)庫   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
//DB2數(shù)據(jù)庫 
Class.froName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();  
//MySQL數(shù)據(jù)庫  Class.forName("com.mysql.jdbc.Driver").newInstance(); 
  1. 建立鏈接    建立數(shù)據(jù)庫之間的連接是訪問數(shù)據(jù)庫的必要條件,就像南水北調(diào)調(diào)水一樣,要想調(diào)水首先由把溝通的河流打通。建立連接對于不同數(shù)據(jù)庫也是不一樣的,下面看一下一些主流數(shù)據(jù)庫建立數(shù)據(jù)庫連接,取得 Connection 對象的不同方式:
 //Oracle8/8i/9i數(shù)據(jù)庫(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數(shù)據(jù)庫 
  String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"; 
  String user="sa"; 
  String password=""; 
  Connection conn=DriverManager.getConnection(url,user,password); 

  //DB2數(shù)據(jù)庫 
  String url="jdbc:db2://localhost:5000/sample"; 
  String user="amdin" 
  String password=-""; 
  Connection conn=DriverManager.getConnection(url,user,password); 

//MySQL數(shù)據(jù)庫 
String url="jdbc:mysql://localhost:3306/testDB?user=root&password=root&useUnicode=true&characterEncoding=gb2312"; 
Connection conn=DriverManager.getConnection(url); 
  1. 執(zhí)行 SQL 語句   數(shù)據(jù)庫連接建立好之后,接下來就是一些準備工作和執(zhí)行 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"); 
做好準備工作之后就可以執(zhí)行sql語句了,執(zhí)行sql語句:
String sql="select * from users"; 
ResultSet rs=stmt.executeQuery(sql); 
//執(zhí)行動態(tài)SQL查詢 
ResultSet rs=pstmt.executeQuery(); 
//執(zhí)行insert update delete等語句,先定義sql 
stmt.executeUpdate(sql); 
  1. 處理結果集   訪問結果記錄集 ResultSet 對象。例如:
  while(rs.next) 
  { 
  out.println("你的第一個字段內(nèi)容為:"+rs.getString("Name")); 
  out.println("你的第二個字段內(nèi)容為:"+rs.getString(2)); 
  } 
  1. 關閉數(shù)據(jù)庫 依次將 ResultSet、Statement、PreparedStatement、Connection 對象關閉,釋放所占用的資源.例如:
  rs.close(); 
  stmt.clost(); 
  pstmt.close(); 
  con.close();

二:JDBC 事務 什么是事務: 首先,說說什么事務。我認為事務,就是一組操作數(shù)據(jù)庫的動作集合。 事務是現(xiàn)代數(shù)據(jù)庫理論中的核心概念之一。如果一組處理步驟或者全部發(fā)生或者一步也不執(zhí)行,我們稱該組處理步驟為一個事務。當所有的步驟像一個操 作一樣被完整地執(zhí)行,我們稱該事務被提交。由于其中的一部分或多步執(zhí)行失敗,導致沒有步驟被提交,則事務必須回滾到最初的系統(tǒng)狀態(tài)。 事務必須服從 ISO/IEC 所制定的 ACID 原則。ACID 是原子性(atomicity)、一致性(consistency)、隔離性 (isolation)和持久性(durability)的縮寫。事務的原子性表示事務執(zhí)行過程中的任何失敗都將導致事務所做的任何修改失效。一致性表示 當事務執(zhí)行失敗時,所有被該事務影響的數(shù)據(jù)都應該恢復到事務執(zhí)行前的狀態(tài)。隔離性表示在事務執(zhí)行過程中對數(shù)據(jù)的修改,在事務提交之前對其他事務不可見。持久性表示當系統(tǒng)或介質(zhì)發(fā)生故障時,確保已提交事務的更新不能丟失。持久性通過數(shù)據(jù)庫備份和恢復來保證。 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 事務的一個缺點是事務的范圍局限于一個數(shù)據(jù)庫連接。一個 JDBC 事務不能跨越多個數(shù)據(jù)庫。 三:java 操作數(shù)據(jù)庫連接池 在總結 java 操作數(shù)據(jù)庫連接池發(fā)現(xiàn)一篇很好的文章,所以就不做具體總結了,直接上地址: http://www.blogjava.net/chunkyo/archive/2007/01/16/94266.html 最后附一段比較經(jīng)典的代碼吧:

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Vector;
public class ConnectionPool {
private String jdbcDriver = ""; // 數(shù)據(jù)庫驅(qū)動
private String dbUrl = ""; // 數(shù)據(jù) URL
private String dbUsername = ""; // 數(shù)據(jù)庫用戶名
private String dbPassword = ""; // 數(shù)據(jù)庫用戶密碼
private String testTable = ""; // 測試連接是否可用的測試表名,默認沒有測試表
private int initialConnections = 10; // 連接池的初始大小
private int incrementalConnections = 5;// 連接池自動增加的大小
private int maxConnections = 50; // 連接池最大的大小
private Vector connections = null; // 存放連接池中數(shù)據(jù)庫連接的向量 , 初始時為 null

// 它中存放的對象為 PooledConnection 型

/**
* 構造函數(shù)
*
* @param jdbcDriver String JDBC 驅(qū)動類串
* @param dbUrl String 數(shù)據(jù)庫 URL
* @param dbUsername String 連接數(shù)據(jù)庫用戶名
* @param dbPassword String 連接數(shù)據(jù)庫用戶的密碼
*
*/

public ConnectionPool(String jdbcDriver,String dbUrl,String dbUsername,String dbPassword) {
         this.jdbcDriver = jdbcDriver;
         this.dbUrl = dbUrl;
         this.dbUsername = dbUsername; 
         this.dbPassword = dbPassword;
}

/**

* 返回連接池的初始大小
*
* @return 初始連接池中可獲得的連接數(shù)量
*/
public int getInitialConnections() {

         return this.initialConnections;
}

/**

* 設置連接池的初始大小

*

* @param 用于設置初始連接池中連接的數(shù)量

*/

public void setInitialConnections(int initialConnections) {
         this.initialConnections = initialConnections;
}

/**

* 返回連接池自動增加的大小 、
*
* @return 連接池自動增加的大小
*/
public int getIncrementalConnections() {

         return this.incrementalConnections;

}

/**
* 設置連接池自動增加的大小
* @param 連接池自動增加的大小
*/

public void setIncrementalConnections(int incrementalConnections) {

         this.incrementalConnections = incrementalConnections;

}

/**
* 返回連接池中最大的可用連接數(shù)量
* @return 連接池中最大的可用連接數(shù)量
*/

public int getMaxConnections() {
         return this.maxConnections;
}

/**

* 設置連接池中最大可用的連接數(shù)量

*

* @param 設置連接池中最大可用的連接數(shù)量值

*/

public void setMaxConnections(int maxConnections) {

         this.maxConnections = maxConnections;

}

/**

* 獲取測試數(shù)據(jù)庫表的名字
*
* @return 測試數(shù)據(jù)庫表的名字
*/
public String getTestTable() {

         return this.testTable;

}

/**
* 設置測試表的名字
* @param testTable String 測試表的名字
*/
public void setTestTable(String testTable) {
         this.testTable = testTable;
}

/**

*
* 創(chuàng)建一個數(shù)據(jù)庫連接池,連接池中的可用連接的數(shù)量采用類成員
* initialConnections 中設置的值
*/
public synchronized void createPool() throws Exception {

         // 確保連接池沒有創(chuàng)建

         // 如果連接池己經(jīng)創(chuàng)建了,保存連接的向量 connections 不會為空

         if (connections != null) {

          return; // 如果己經(jīng)創(chuàng)建,則返回

         }

         // 實例化 JDBC Driver 中指定的驅(qū)動類實例

         Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance());

         DriverManager.registerDriver(driver); // 注冊 JDBC 驅(qū)動程序

         // 創(chuàng)建保存連接的向量 , 初始時有 0 個元素

         connections = new Vector();

         // 根據(jù) initialConnections 中設置的值,創(chuàng)建連接。

         createConnections(this.initialConnections);

         System.out.println(" 數(shù)據(jù)庫連接池創(chuàng)建成功! ");

}

/**

* 創(chuàng)建由 numConnections 指定數(shù)目的數(shù)據(jù)庫連接 , 并把這些連接

* 放入 connections 向量中
*
* @param numConnections 要創(chuàng)建的數(shù)據(jù)庫連接的數(shù)目
*/
@SuppressWarnings("unchecked")
private void createConnections(int numConnections) throws SQLException {

         // 循環(huán)創(chuàng)建指定數(shù)目的數(shù)據(jù)庫連接

         for (int x = 0; x < numConnections; x++) {

          // 是否連接池中的數(shù)據(jù)庫連接的數(shù)量己經(jīng)達到最大?最大值由類成員 maxConnections

          // 指出,如果 maxConnections 為 0 或負數(shù),表示連接數(shù)量沒有限制。

          // 如果連接數(shù)己經(jīng)達到最大,即退出。

          if (this.maxConnections > 0 && this.connections.size() >= this.maxConnections) {

           break;

          }

          //add a new PooledConnection object to connections vector

          // 增加一個連接到連接池中(向量 connections 中)

          try{

           connections.addElement(new PooledConnection(newConnection()));

          }catch(SQLException e){

           System.out.println(" 創(chuàng)建數(shù)據(jù)庫連接失??! "+e.getMessage());

          throw new SQLException();

          }

          System.out.println(" 數(shù)據(jù)庫連接己創(chuàng)建 ......");

         }
}

/**

* 創(chuàng)建一個新的數(shù)據(jù)庫連接并返回它
*
* @return 返回一個新創(chuàng)建的數(shù)據(jù)庫連接
*/
private Connection newConnection() throws SQLException {

         // 創(chuàng)建一個數(shù)據(jù)庫連接

         Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);

         // 如果這是第一次創(chuàng)建數(shù)據(jù)庫連接,即檢查數(shù)據(jù)庫,獲得此數(shù)據(jù)庫允許支持的

         // 最大客戶連接數(shù)目

         //connections.size()==0 表示目前沒有連接己被創(chuàng)建

         if (connections.size() == 0) {

          DatabaseMetaData metaData = conn.getMetaData();

          int driverMaxConnections = metaData.getMaxConnections();

          // 數(shù)據(jù)庫返回的 driverMaxConnections 若為 0 ,表示此數(shù)據(jù)庫沒有最大

          // 連接限制,或數(shù)據(jù)庫的最大連接限制不知道

          //driverMaxConnections 為返回的一個整數(shù),表示此數(shù)據(jù)庫允許客戶連接的數(shù)目

          // 如果連接池中設置的最大連接數(shù)量大于數(shù)據(jù)庫允許的連接數(shù)目 , 則置連接池的最大

          // 連接數(shù)目為數(shù)據(jù)庫允許的最大數(shù)目

          if (driverMaxConnections > 0 && this.maxConnections > driverMaxConnections) {

           this.maxConnections = driverMaxConnections;

          }
         } 
         return conn; // 返回創(chuàng)建的新的數(shù)據(jù)庫連接

}

/**

* 通過調(diào)用 getFreeConnection() 函數(shù)返回一個可用的數(shù)據(jù)庫連接 ,

* 如果當前沒有可用的數(shù)據(jù)庫連接,并且更多的數(shù)據(jù)庫連接不能創(chuàng)

* 建(如連接池大小的限制),此函數(shù)等待一會再嘗試獲取。

*

* @return 返回一個可用的數(shù)據(jù)庫連接對象

*/

public synchronized Connection getConnection() throws SQLException {

         // 確保連接池己被創(chuàng)建

         if (connections == null) {

          return null; // 連接池還沒創(chuàng)建,則返回 null

         }

         Connection conn = getFreeConnection(); // 獲得一個可用的數(shù)據(jù)庫連接

         // 如果目前沒有可以使用的連接,即所有的連接都在使用中

         while (conn == null){

          // 等一會再試

          wait(250);

          conn = getFreeConnection(); // 重新再試,直到獲得可用的連接,如果

          //getFreeConnection() 返回的為 null

          // 則表明創(chuàng)建一批連接后也不可獲得可用連接

         }

         return conn;// 返回獲得的可用的連接
}

/**

* 本函數(shù)從連接池向量 connections 中返回一個可用的的數(shù)據(jù)庫連接,如果

* 當前沒有可用的數(shù)據(jù)庫連接,本函數(shù)則根據(jù) incrementalConnections 設置

* 的值創(chuàng)建幾個數(shù)據(jù)庫連接,并放入連接池中。

* 如果創(chuàng)建后,所有的連接仍都在使用中,則返回 null

* @return 返回一個可用的數(shù)據(jù)庫連接

*/

private Connection getFreeConnection() throws SQLException {

         // 從連接池中獲得一個可用的數(shù)據(jù)庫連接

         Connection conn = findFreeConnection();

         if (conn == null) {

          // 如果目前連接池中沒有可用的連接

          // 創(chuàng)建一些連接

          createConnections(incrementalConnections);

          // 重新從池中查找是否有可用連接

          conn = findFreeConnection();

          if (conn == null) {

           // 如果創(chuàng)建連接后仍獲得不到可用的連接,則返回 null

           return null;

          }

         }

         return conn;

}

/**

* 查找連接池中所有的連接,查找一個可用的數(shù)據(jù)庫連接,

* 如果沒有可用的連接,返回 null

*

* @return 返回一個可用的數(shù)據(jù)庫連接

*/

private Connection findFreeConnection() throws SQLException {

         Connection conn = null;

         PooledConnection pConn = null;

         // 獲得連接池向量中所有的對象

         Enumeration enumerate = connections.elements();

         // 遍歷所有的對象,看是否有可用的連接

         while (enumerate.hasMoreElements()) {

          pConn = (PooledConnection) enumerate.nextElement();

          if (!pConn.isBusy()) {

           // 如果此對象不忙,則獲得它的數(shù)據(jù)庫連接并把它設為忙

           conn = pConn.getConnection();

           pConn.setBusy(true);

           // 測試此連接是否可用

           if (!testConnection(conn)) {

            // 如果此連接不可再用了,則創(chuàng)建一個新的連接,

            // 并替換此不可用的連接對象,如果創(chuàng)建失敗,返回 null

            try{

             conn = newConnection();

            }catch(SQLException e){

             System.out.println(" 創(chuàng)建數(shù)據(jù)庫連接失敗! "+e.getMessage());

             return null;

            }

            pConn.setConnection(conn);

           }

           break; // 己經(jīng)找到一個可用的連接,退出

          }

         }

         return conn;// 返回找到到的可用連接

}

/**

* 測試一個連接是否可用,如果不可用,關掉它并返回 false

* 否則可用返回 true

*

* @param conn 需要測試的數(shù)據(jù)庫連接

* @return 返回 true 表示此連接可用, false 表示不可用

*/

private boolean testConnection(Connection conn) {

         try {

          // 判斷測試表是否存在

          if (testTable.equals("")) {

           // 如果測試表為空,試著使用此連接的 setAutoCommit() 方法

           // 來判斷連接否可用(此方法只在部分數(shù)據(jù)庫可用,如果不可用 ,

           // 拋出異常)。注意:使用測試表的方法更可靠

           conn.setAutoCommit(true);

          } else {// 有測試表的時候使用測試表測試

           //check if this connection is valid

           Statement stmt = conn.createStatement();

           stmt.execute("select count(*) from " + testTable);

          }

         } catch (SQLException e) {

          // 上面拋出異常,此連接己不可用,關閉它,并返回 false;

          closeConnection(conn);

          return false;

         }

         // 連接可用,返回 true

         return true;

}

/**

* 此函數(shù)返回一個數(shù)據(jù)庫連接到連接池中,并把此連接置為空閑。

* 所有使用連接池獲得的數(shù)據(jù)庫連接均應在不使用此連接時返回它。

*

* @param 需返回到連接池中的連接對象

*/

public void returnConnection(Connection conn) {

         // 確保連接池存在,如果連接沒有創(chuàng)建(不存在),直接返回

         if (connections == null) {

          System.out.println(" 連接池不存在,無法返回此連接到連接池中 !");

          return;

         }

         PooledConnection pConn = null;

         Enumeration enumerate = connections.elements();

         // 遍歷連接池中的所有連接,找到這個要返回的連接對象

         while (enumerate.hasMoreElements()) {

          pConn = (PooledConnection) enumerate.nextElement();

          // 先找到連接池中的要返回的連接對象

          if (conn == pConn.getConnection()) {

           // 找到了 , 設置此連接為空閑狀態(tài)

           pConn.setBusy(false);

           break;

          }

         }

}

/**

* 刷新連接池中所有的連接對象

*

*/

public synchronized void refreshConnections() throws SQLException {

         // 確保連接池己創(chuàng)新存在

         if (connections == null) {

          System.out.println(" 連接池不存在,無法刷新 !");

          return;

         }

         PooledConnection pConn = null;

         Enumeration enumerate = connections.elements();

         while (enumerate.hasMoreElements()) {

          // 獲得一個連接對象

          pConn = (PooledConnection) enumerate.nextElement();

          // 如果對象忙則等 5 秒 ,5 秒后直接刷新

          if (pConn.isBusy()) {

           wait(5000); // 等 5 秒

          }

          // 關閉此連接,用一個新的連接代替它。

          closeConnection(pConn.getConnection());

          pConn.setConnection(newConnection());

          pConn.setBusy(false);

         }

}

/**

* 關閉連接池中所有的連接,并清空連接池。

*/

public synchronized void closeConnectionPool() throws SQLException {

         // 確保連接池存在,如果不存在,返回

         if (connections == null) {

          System.out.println(" 連接池不存在,無法關閉 !");

          return;

         }

         PooledConnection pConn = null;

         Enumeration enumerate = connections.elements();

         while (enumerate.hasMoreElements()) {

          pConn = (PooledConnection) enumerate.nextElement();

          // 如果忙,等 5 秒

          if (pConn.isBusy()) {

           wait(5000); // 等 5 秒

          }

         //5 秒后直接關閉它

         closeConnection(pConn.getConnection());

         // 從連接池向量中刪除它

         connections.removeElement(pConn);

         }

         // 置連接池為空

         connections = null;

}

/**

* 關閉一個數(shù)據(jù)庫連接

*

* @param 需要關閉的數(shù)據(jù)庫連接

*/

private void closeConnection(Connection conn) {

         try {

          conn.close();

         }catch (SQLException e) {

          System.out.println(" 關閉數(shù)據(jù)庫連接出錯: "+e.getMessage());

         }

}

/**

* 使程序等待給定的毫秒數(shù)

*

* @param 給定的毫秒數(shù)

*/

private void wait(int mSeconds) {

         try {

          Thread.sleep(mSeconds);

         } catch (InterruptedException e) {

         }

}

/**

*

* 內(nèi)部使用的用于保存連接池中連接對象的類

* 此類中有兩個成員,一個是數(shù)據(jù)庫的連接,另一個是指示此連接是否

* 正在使用的標志。

*/

class PooledConnection {

         Connection connection = null;// 數(shù)據(jù)庫連接

         boolean busy = false; // 此連接是否正在使用的標志,默認沒有正在使用

         // 構造函數(shù),根據(jù)一個 Connection 構告一個 PooledConnection 對象

         public PooledConnection(Connection connection) {

          this.connection = connection;

         }

         // 返回此對象中的連接

         public Connection getConnection() {

          return connection;

         }

         // 設置此對象的,連接

         public void setConnection(Connection connection) {

          this.connection = connection;

         }

         // 獲得對象連接是否忙

         public boolean isBusy() {

          return busy;

         }

         // 設置對象的連接正在忙

         public void setBusy(boolean busy) {

          this.busy = busy;

         }

}

}

=======================================

這個例子是根據(jù)POSTGRESQL數(shù)據(jù)庫寫的,
請用的時候根據(jù)實際的數(shù)據(jù)庫調(diào)整。

調(diào)用方法如下:

① ConnectionPool connPool
                                     = new ConnectionPool("org.postgresql.Driver"
                                                                         ,"jdbc:postgresql://dbURI:5432/DBName"
                                                                         ,"postgre"
                                                                         ,"postgre");

② connPool .createPool();
  Connection conn = connPool .getConnection();
上一篇:常見設計模式下一篇:JDBC