Demo Get Generated Keys MySQL : Key « Database SQL JDBC « Java





Demo Get Generated Keys MySQL

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

public class DemoGetGeneratedKeysMySQL {
  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;
    try {
      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);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    } finally {
      try {
        rs.close();
        stmt.close();
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}
           
       










Related examples in the same category

1.Get Foreign Keys
2.Get Imported Keys
3.Get Primary Key Column From A Table