Java Jdbc 串連 Oracle 執行簡單查詢樣本:
package com.test.dbtest;import java.sql.CallableStatement;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;/**Jdbc 串連 Oracle 資料庫 簡單樣本 *@author wanggq *@version 建立時間:2014年3月31日 上午11:00:06 *類說明 */public class TestO_procedure01 {public static void main(String[] args) {String driver = "oracle.jdbc.driver.OracleDriver";String url = "jdbc:Oracle:thin:@localhost:1521:orcl";Statement stmt = null;ResultSet res = null;Connection conn = null;CallableStatement proc = null;String sql = " select T.REC_NO, T.AIRLINE,T.DEPARTURE,T.ARRIVAL from CDP_MAIN_ORDER t where t.departure=upper('pek')";try {Class.forName(driver);conn = DriverManager.getConnection(url, "abc123", "abc123");stmt = conn.createStatement();res = stmt.executeQuery(sql);while(res.next()){String rec = res.getString("REC_NO");String airline = res.getString("AIRLINE");String dept = res.getString("DEPARTURE");String arr = res.getString("ARRIVAL");System.out.println(rec+" "+airline+" "+dept+" "+arr);}} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
也可以使用防止SQL注入PreparedStatement方法
PreparedStatement stmt = null;ResultSet res = null;Connection conn = null;CallableStatement proc = null;String sql = " select T.REC_NO, T.AIRLINE,T.DEPARTURE,T.ARRIVAL from CDP_MAIN_ORDER t where t.departure=upper(?)";try {Class.forName(driver);conn = DriverManager.getConnection(url, "abc123", "abc123");stmt = conn.prepareStatement(sql);stmt.setString(1, "pek");res = stmt.executeQuery();
DB: