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 block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.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: