没有序列列,Java JDBC无法获取生成的键

时间:2018-10-02 09:21:05

标签: java jdbc spring-jdbc jdbctemplate

if (Baglan() == false) { return false; }
    try{
        String generatedColumns[] = {"ID","TAHSILATNO"};            
        String sSql = "Declare nId number := 0;" + 
                "        nKey number := 0;" + 
                " BEGIN" + 
                "   Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" +
                "   INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, 53);" + 
                "   EXCEPTION " + 
                "     WHEN DUP_VAL_ON_INDEX THEN" + 
                "          Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" + 
                "          Select Nvl(Max(tahsilatno),0) + 1 INTO nKey From bvktahsilatno WHERE Yili = 2018;" +
                "          INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, nKey);" + 
                "END;";

        //VtStatement = VtConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        //VtStatement.execute(pSql);
        //PreparedStatement  VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS );
        //PreparedStatement  VtStatement = VtConnection.prepareStatement( sSql, generatedColumns );

        PreparedStatement  VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS);
        System.out.println("oracle cumle : "  + sSql);          
        int nAdet = VtStatement.executeUpdate();
        System.out.println("Hatayok/Adet : " + nAdet);

        ResultSet rs = VtStatement.getGeneratedKeys();

        int id=0;
        while (rs.next()) {
             id = rs.getInt(1);

        }           
        System.out.println("Oracle Inserted ID -" + id); // display inserted record

        return true;
    } catch (SQLException e) {                      
        return false;
    }

我想问一个有关在插入查询后在Oracle Db上检索创建的键的问题。我的代码如上所述,但是生成的键值未显示在终端上。如何在不创建序列的情况下获取生成的列值?许多表单页面都说,有可能对id或其他列使用序列。 id是主键,tahsilatno是唯一索引。我可以克服这个问题吗? 谢谢您从现在开始的帮助

0 个答案:

没有答案