Statement: getGeneratedKeys() : Statement « java.sql « Java by API






Statement: getGeneratedKeys()

 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Main {
  public static Connection getConnection() throws Exception {
    String driver = "org.gjt.mm.mysql.Driver";
    String url = "jdbc:mysql://localhost/databaseName";
    String username = "root";
    String password = "root";

    Class.forName(driver);
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }

  public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement stmt = null;
    ResultSet rs = null;
    conn = getConnection();
    stmt = conn.createStatement();
    stmt.executeUpdate("insert into animals_table (name) values('newName')");
    rs = stmt.getGeneratedKeys();
    while (rs.next()) {
      ResultSetMetaData rsMetaData = rs.getMetaData();
      int columnCount = rsMetaData.getColumnCount();

      for (int i = 1; i <= columnCount; i++) {
        String key = rs.getString(i);
        System.out.println("key " + i + " is " + key);
      }
    }
    rs.close();
    stmt.close();
    conn.close();
  }
}

   
  








Related examples in the same category

1.Statement.EXECUTE_FAILED
2.Statement.RETURN_GENERATED_KEYS
3.Statement.SUCCESS_NO_INFO
4.Statement: addBatch(String sql)
5.WebRowSet: execute(Connection conn)
6.Statement: executeBatch()
7.Statement: executeQuery(String sql)
8.Statement: getFetchSize()
9.Statement: getMaxFieldSize()
10.Statement: getMaxRows()
11.Statement: getQueryTimeout()
12.WebRowSet: setCommand(String cmd)
13.Statement: setFetchSize(int rows)