表結構:
create table test( id varchar2(32) primary key, name varchar2(32) );
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Test { /** * 使用Statement.RETURN_GENERATED_KEYS 指定返回生成主鍵 */ public static void main(String[] args) { PreparedStatement pst = null; ResultSet rs = null; Connection conn = ConnectionManager.getConnection(); String sql = "insert into test(id,name) values(?,?)"; try { //String generatedColumns[] = { "ID" }; //獲得指定ID pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); // 指定返回生成的主鍵 pst.setString(1, "123x"); pst.setString(2, "test"); int ii = pst.executeUpdate(); // 檢索對象生成的鍵 rs = pst.getGeneratedKeys(); if (rs.next()) { System.out.println("數據主鍵:" + rs.getString(1)); } ConnectionManager.closeAll(rs, pst, conn); // 關閉資源 } catch (SQLException e) { e.printStackTrace(); } } }以下是JDBC輔助類,不是本文重點
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ConnectionManager { public static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String URL = "jdbc:oracle:thin:@localhost:1521/orcl"; public static final String USERNAME = "root"; public static final String PASSWORD = "root"; /** * 通過靜態代碼塊 注冊數據庫驅動 */ static{ try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 獲得Connection * * @return */ public static Connection getConnection() { Connection conn = null; try { conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); }catch (SQLException e) { e.printStackTrace(); } return conn; } /** * 關閉ResultSet * @param rs */ public static void closeResultSet(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 關閉Statement * @param st */ public static void closeStatement(Statement st) { if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 關閉Connection * @param conn */ public static void closeConnection(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 關閉全部 * @param rs * @param sta * @param conn */ public static void closeAll(ResultSet rs,Statement sta,Connection conn){ closeConnection(conn); closeStatement(sta); closeResultSet(rs); } }
其實是test表的ROWID字段值
String generatedColumns[] = { "ID" }; pst = conn.prepareStatement(sql, generatedColumns);