1. 首頁
  2. 資料庫作業系統

Java資料庫程式設計中的幾個常用技巧

Java資料庫程式設計中的幾個常用技巧

1、java資料庫操作基本流程

2、幾個常用的重要技巧:

可滾動、更新的記錄集

批次更新

事務處理

java資料庫操作基本流程:取得資料庫連線 - 執行sql語句 - 處理執行結果 - 釋放資料庫連線

1、取得資料庫連線

1)用DriverManager取資料庫連線

例子:

String className,url,uid,pwd;

className = "oracle.jdbc.driver.OracleDriver";

url = "jdbc:oracle:thin:@127.0.0.1:1521:orasvr;

uid = "system";

pwd = "manager";

Class.forName(className);

Connection cn = DriverManager.getConnection(url,uid,pwd);

2)用jndi(java的命名和目錄服務)方式

例子

String jndi = "jdbc/db";

Context ctx = (Context) new InitialContext().lookup("java:comp/env");

DataSource ds = (DataSource) ctx.lookup(jndi);

Connection cn = ds.getConnection();

多用於jsp中

2、執行sql語句

1)用Statement來執行sql語句

String sql;

Statement sm = cn.createStatement();

sm.executeQuery(sql); // 執行資料查詢語句(select)

sm.executeUpdate(sql); // 執行資料更新語句(、update、、drop等)statement.close();

2)用PreparedStatement來執行sql語句

String sql;

sql = " into user (id,name) values (?,?)";

PreparedStatement ps = cn.prepareStatement(sql);

ps.setInt(1,xxx);

ps.setString(2,xxx);

...

ResultSet rs = ps.executeQuery(); // 查詢

int c = ps.executeUpdate(); // 更新

3、處理執行結果

查詢語句,返回記錄集ResultSet。

更新語句,返回數字,表示該更新影響的記錄數。

ResultSet的方法:

1、next(),將遊標往後移動一行,如果成功返回true;否則返回false。

2、getInt("id")或getSting("name"),返回當前遊標下某個欄位的值。

3、釋放連線。

cn.close();

一般,先關閉ResultSet,然後關閉Statement(或者PreparedStatement);最後關閉Connection

可滾動、更新的記錄集

1、建立可滾動、更新的Statement

Statement sm = cn.createStatement(ResultSet.TYPE_SCROLL_ENSITIVE,ResultSet.CONCUR_READ_ONLY);

該Statement取得的ResultSet就是可滾動的

2、建立PreparedStatement時指定引數

PreparedStatemet ps = cn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

ResultSet.absolute(9000);

批次更新

1、Statement

Statement sm = cn.createStatement();

sm.addBatch(sql1);

sm.addBatch(sql2);

...

sm.executeBatch()

一個Statement物件,可以執行多個sql語句以後,批次更新。這多個語句可以是、update、等或兼有

2、PreparedStatement

PreparedStatement ps = cn.preparedStatement(sql);

{

ps.setXXX(1,xxx);

...

ps.addBatch();

}

ps.executeBatch();

一個PreparedStatement,可以把一個sql語句,變換引數多次執行,一次更新。

事務的`處理

1、關閉Connection的自動提交

cn.setAutoCommit(false);

2、執行一系列sql語句

要點:執行每一個新的sql語句前,上一次執行sql語句的Statement(或者PreparedStatemet)必須先close

Statement sm ;

sm = cn.createStatement( into user...);

sm.executeUpdate();

sm.close();

sm = cn.createStatement(" into corp...);

sm.executeUpdate();

sm.close();

3、提交

cn.commit();

4、如果發生異常,那麼回滾

cn.rollback();