devxlogo

Get the Keys for Rows Added by an INSERT Statement

Get the Keys for Rows Added by an INSERT Statement

This tip shows how to get the keys generated for the rows added by an INSERT statement.

Statement st=null;PreparedStatement pst=null;Connection conn=null;ResultSet rs=null;ResultSetMetaData rsmd=null;...try {    st= conn.createStatement();    }catch (SQLException e)       {System.out.println(e.getMessage());}try {    pst= new conn.prepareStatement(INSERT INTO table_name (field1, field2, ...) VALUES](?, ?, ...),Statement.RETURN_GENERATED_KEYS);              pst.settype(1,val_1);             pst.settype(2,val_2);             ...            pst.settype(n,val_n);             pst.executeUpdate();             rs =pst.getGeneratedKeys();             if (!rs.next())System.out.println(No keys!);               else               {               rsmd = rs.getMetaData();               while (rs.next())               {               for (int i = 1; i <= rsmd.getColumnCount(); i++)                  {                 String ch = rs.getString(i);                 System.out.println("ch{" + i + "}:" + ch);                 }               }          }     }catch (SQLException e)        {System.out.println(e.getMessage());}...
See also  What Are International Payments, And How Do They Work?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist