Java資料庫編程常用技巧

來源:互聯網
上載者:User

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();
// 更新

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.