Java資料庫編程中的幾個常用技巧

來源:互聯網
上載者:User
、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); // 執行資料更新語句(delete、update、insert、drop等)statement.close();
  2)用PreparedStatement來執行sql語句
String sql;
sql = "insert 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.