17,377
社区成员
发帖
与我相关
我的任务
分享
SQL> select * from test_2;
ID NAME DISTR
---------- -------------------- -----
1 xiaoming S
2 xiaohua S
3 xiaosheng P
SQL> set serveroutput on
SQL>
SQL> declare
2 id number;
3 begin
4 insert into test_2 values(4,'xiaohuang','S')
5 returning id into id;
6 commit;
7 dbms_output.put_line(id);
8 end;
9 /
4
PL/SQL procedure successfully completed
package test.oracle;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import test.oracle.conn.OConnection;
public class TestGetSeqInsert {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = OConnection.getConn();
DatabaseMetaData dmd = con.getMetaData();
System.out.println("database product name: "
+ dmd.getDatabaseProductName());
System.out.println("database product version: "
+ dmd.getDatabaseProductVersion());
System.out.println("supports generate keys? "
+ dmd.supportsGetGeneratedKeys());
String sql = "INSERT INTO test11 " + "VALUES (t_seq.nextval, ?)";
ps = con.prepareStatement(sql, new String[] { "ID" }); // 后面一个参数表示需要返回的列名
ps.setTimestamp(1, new Timestamp(System.currentTimeMillis()));
ps.executeUpdate();
if (dmd.supportsGetGeneratedKeys()) {
rs = ps.getGeneratedKeys();
while (rs.next()) {
// 如果使用 rs.getInt("ID") 会报错,奇怪的 Oracle JDBC 驱动!
System.out.println("ID: " + rs.getInt(1));
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}