Created
April 14, 2016 04:25
-
-
Save jpt1122/e7757e6944d26115856b90220de5263b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.sql.Statement; | |
public class JDBCGetAutoIncKeys { | |
private static final String DBURL = | |
"jdbc:mysql://localhost:3306/mydb?user=usr&password=sql" + | |
"&useUnicode=true&characterEncoding=UTF-8"; | |
private static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; | |
static { | |
try { | |
Class.forName(DBDRIVER).newInstance(); | |
} catch (Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
private static Connection getConnection() | |
{ | |
Connection connection = null; | |
try { | |
connection = DriverManager.getConnection(DBURL); | |
} | |
catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return connection; | |
} | |
public static void main(String[] args) { | |
Statement stmt = null; | |
ResultSet rs = null; | |
Connection conn = null; | |
try { | |
conn = getConnection(); | |
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, | |
java.sql.ResultSet.CONCUR_UPDATABLE); | |
stmt.executeUpdate("DROP TABLE IF EXISTS autoincSample"); | |
stmt.executeUpdate( | |
"CREATE TABLE autoincSample (" | |
+ "id INT NOT NULL AUTO_INCREMENT, " | |
+ "data VARCHAR(64), PRIMARY KEY (id))"); | |
stmt.executeUpdate( | |
"INSERT INTO autoincSample (data) " | |
+ "values ('Record ----- 1')", | |
Statement.RETURN_GENERATED_KEYS); | |
rs = stmt.getGeneratedKeys(); | |
while (rs.next()) { | |
System.out.println("Key returned from getGeneratedKeys():" | |
+ rs.getInt(1)); | |
} | |
rs.close(); | |
} | |
catch(Exception e) { | |
e.printStackTrace(); | |
} | |
finally { | |
if (rs != null) { | |
try { | |
rs.close(); | |
} catch (SQLException ex) { | |
} | |
} | |
if (stmt != null) { | |
try { | |
stmt.close(); | |
} catch (SQLException ex) { | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment