本文章為看Java學(xué)習(xí)視頻的學(xué)習(xí)筆記,供自己以后參考學(xué)習(xí)。JDBC為Java提供的唯一一個(gè)和各個(gè)數(shù)據(jù)庫(kù)進(jìn)行交互的接口庫(kù)。
JDBC編程步驟
JDBC的編程步驟比較固定,核心步驟如下:
- Load the Driver,即加載驅(qū)動(dòng)
創(chuàng)建Driver的方法有下面幾種:
Class.forName() | Class.forName().newInstance() | new DriverName()
在實(shí)例化時(shí)自動(dòng)向DriverManager注冊(cè),因此不需要顯式調(diào)用DriverManager.registerDriver方法。 - Connect to the Database,即連接數(shù)據(jù)庫(kù)
方法為DriverManager.getConnection() - Execute the SQL,執(zhí)行SQL語(yǔ)句
Connection.CreateStatement()
Statement.executeQuery()
Statement.executeUpdate() - Retrieve the result data,獲取查詢結(jié)果
循環(huán)取得結(jié)果:while (rs.next()) - Show the result data,顯示結(jié)果數(shù)據(jù)
將數(shù)據(jù)庫(kù)中的各種類型轉(zhuǎn)換為Java中的類型(getXXX)方法 - Close,關(guān)閉
close theresultset,close thestatement,close theconnection
JDBC程序示例
下面為較為規(guī)范的程序示例,需要注意以下幾點(diǎn):
- 應(yīng)該使用
try...catch...捕獲異常,最好不要用throws拋出異常。 - 將
rs關(guān)閉后要置空,以便于垃圾回收器將占用的內(nèi)存回收。
示例代碼如下:
public class Test {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.1:1521:SXT", "scott", "tiger");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * form dept");
while(rs.next()){
System.out.println(rs.getString("deptno"));
System.out.println(rs.getInt("deptno"));
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(rs != null){
rs.close();
rs = null;
}
if(stmt != null){
stmt.close();
stmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
JDBC進(jìn)階
- 指定SQL語(yǔ)句中的變量,
PreparedStatement
由于原始SQL語(yǔ)句繁瑣,平時(shí)應(yīng)多使用這種語(yǔ)句。 是一種特殊的Statement - 對(duì)存儲(chǔ)過(guò)程進(jìn)行調(diào)用,
CallableStatement
CallableStatement cstmt = conn.prepareCall("{call p(?, ?, ?, ?)}");
cstmt.registerOutParameter(3, Types.INTEGER);
cstmt.registerOutParameter(4, Types.INTEGER);
cstmt.setInt(1, 3);
cstmt.setInt(2, 4);
cstmt.setInt(4, 5);
cstmt.execute();
System.out.println(cstmt.getInt(3));
System.out.println(cstmt.getInt(4));
cstmt.close();
conn.close();
- 批處理
ps.addBatch();
ps.executeBatch();
JDBC處理事務(wù)(Transaction)
處理步驟:
- 將自動(dòng)提交設(shè)為
false
conn.setAutoCommit(false) - 處理相關(guān)邏輯
- 手動(dòng)提交
conn.commit() - 將自動(dòng)提交設(shè)為
true
conn.setAutoCommit(true) - 如果捕獲到任何的
SQLException,則rollback
主要代碼片段:
try{
conn.setAutoCommit(false);
//處理相關(guān)邏輯
conn.commit()
conn.setAutoCommit(true);
} catch(SQLException e) {
e.printStackTrace();
try {
if(conn!=null)
{
conn.rollback();
conn.setAutoCommit(true);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally{
//codes
}