天天看點

JDK6筆記(5)----JDBC4(2)

版權聲明:本文為部落客chszs的原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chszs/article/details/1555630

JDK6筆記(5)----JDBC4(2)

1、了解Statements

有三種類型的Statements:

1)Statements接口

它通常用于隻需不帶參數的SQL語句。

2)PreparedStatement

預準備語句是從Statement接口中繼承的;PreparedStatement對象在你需要提前建立和編譯SQL語句時非常有用。

PreparedStatement對象還接受IN參數,後面将詳述它。

3)CallableStatement

CallableStatement是從預準備語句中繼承的,并且接受IN和OUT參數。

CallableStatement的主要用途是用于執行資料庫存儲過程。

2、研究Statement接口

Statement對象通常用于執行普通SQL語句調用,前提是已建立一個連接配接并且Connection對象存在。

如:

Connection cConn=dsDataSource.getConnection("username","password");

Statement sStatement=cConn.createStatement();

//Execute the following SQL query

ResultSet rsResults=sStatement.executeQuery("SELECT * FROM PLAYBOYS");

while(rsResults.next()){

 //Perform operations

}

有以下的方法:

boolean execute(String sql);

boolean execute(String sql, int autoGenKeys);

boolean execute(String sql, int[] columnIndexes);

boolean execute(String sql, String[] columnNames);

int[] executeBatch(); //執行成批的資料庫指令,傳回更新計算的數組

ResultSet executeQuery(String sql);

int executeUpdate(String sql, int autoGeneratedKeys);

int executeUpdate(String sql, int[] columnIndexes);

int executeUpdate(String sql, String[] columnNames);

總的來說,隻有在SQL語句是靜态的時候才使用statements。如果含參數,你應該使用預準備語句接口,見下面。

3、PreparedStatement Interface

當你要多次執行SQL語句時,預準備語句是你極好的選擇。它提高了程式的efficiency和performance。

PreparedStatement是Statement接口的子類,是以它繼承了上面所列的各種方法。

當使用PreparedStatement對象的execute()方法時,你最好不要嘗試傳遞參數到execute()、executeQuery()、executeUpdate()方法中。

1)設定IN參數

PreparedStatement對象向開發者提供了用于SQL語句的内嵌的IN參數。

無論在SQL語句的哪個地方,在PreparedStatement語句執行前,隻要IN參數出現了,你都必須在你的應用程式中向IN參數填入一個值。填值使用适當的setter方法。如下:

(1)void setBoolean(int paramIndex, boolean x);

設定IN參數為一個布爾值;

(2)void setDate(int paramIndex, Date x);

設定IN參數為java.sql.Date值;

(3)void setDouble(int paramIndex, double x);

(4)void setFloat(int paramIndex, float x);

(5)void setInt(int paramIndex, int x);

(6)void setLong(int paramIndex, long x);

(7)void setString(int paramIndex, String x);

(8)void clearParameters();

清除通過setter方法設定的參數值的集。

預準備語句接口的典型用法如下:

一個名為CAR的表,定義如下:

CREATE TABLE CAR(

 ID INTEGER NOT NULL,

 MODEL VARCHAR(28),

 MODEL_YEAR VARCHAR(10)

 );

相一緻的CAR類如下:

public class Car{

 Long id;

 String model;

 String year;

 //set 和 get 方法

 }

下面,建立一個執行查詢的方法,傳回比對你的選擇條件的cars集。

public Collection<Car> getAllCars(String year){

 Collection<Car> cars=new ArrayList<Car>();

 Connection con=null;

 PreparedStatement stmt=null;

 ResultSet rs=null;

 try{

  String url="jdbc:derby://localhost:9527/mydb;create=true";

  con=DriverManager.getConnection(url,"sa","password");

  String sql="SELECT ID,MODEL,MODEL_YEAR FROM CAR WHERE MODEL_YEAR=?";

  stmt=con.prepareStatement(sql);

  stmt.setString(1,year);

  rs=stmt.executeQuery();

把結果儲存到對象集中。

while(rs.next()){

 System.out.println("result");

 Car car=new Car();

 long id=rs.getLong("ID");

 String model=rs.getString("MODEL");

 String modelyear=rs.getString("MODEL_YEAR");

 car.setID(id);

 car.setModel(model);

 car.setYear(modelyear);

 cars.add(car);

}catch(SQLException e){}

在JDBC4.0中,你可以通過exception chain(例外鍊)來浏覽:

while(ex!=null){

 System.out.println("SQLState:"+ex.getSQLState());

 System.out.println("Error Code:"+ex.getErrorCode());

 System.out.println("Message:"+ex.getMessage());

 Throwable t=ex.getCause();

 while(t!=null){

  System.out.println("Cause:"+t);

  t=t.getCause();

  }

 ex=ex.getNextException();

最後是重要的一點,關閉ResultSet,Statement,Connection。

}finally{

  if(rs!=null) rs.close();

  if(stmt!=null) stmt.close();

  if(con!=null) con.close();

 }catch(SQLException e){}

 return cars;

總結:上面的代碼有很多備援,在下一節我将讨論兩種減少重複代碼的方法:Annotation和Hibernate。