Demo Get Generated Keys MySQL : Key : Database SQL JDBC : Java examples (example source code) Organized by topic

Java
C++
PHP
Java Home »  Database SQL JDBC   » [  Key  ]  Screenshots 
 



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 KeysHas Download File
2.  Get Imported KeysHas Download File
3.  Get Primary Key Column From A TableHas Download File








Home| Contact Us
Copyright 2003 - 04 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.