JDBC Insert语句插入Oracle数据库返回数据主键
表结构:
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 = "hrmis"; public static final String PASSWORD = "hrmis"; /** * 通过静态代码块 注册数据库驱动 */ 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); } }
控制台打印:
数据主键:AAAT2zAANAAACalAAB
而我们的主键是ID值为123x.那打印的AAAT2zAANAAACalAAB是什么玩意呢,使用rs.getObject(1)在控制台打印,显示如下:
数据主键:oracle.sql.ROWID@452bb7e0
其实是test表的ROWID字段值
如果要获得指定的ID字段值 可以用如下方法:
String generatedColumns[] = { "ID" }; pst = conn.prepareStatement(sql, generatedColumns);