Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Apr 17, 2007

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());}
...
Leonard Anghel
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap