블로그 이미지

calendar

1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
  • total
  • today
  • yesterday
2011. 10. 5. 21:27 JAVA언어

다음은 MySQL JDBC INSERT 시 AUTO INCREMENT 값을 알아내는 예제이다.

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

public class MySQLJdbcExample {

public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "apmsetup";
try {
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();

String sql = "INSERT INTO auto_increment_test_table (name) VALUE ('test')";
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
int autoIncrement = rs.getInt(1);
System.out.println("autoIncrement: " + autoIncrement);
}

}

위 예제는 JDBC의 기능을 활용한 버전이었고,

이번에는 MySQL의 SQL 문을 활용하는 버전이다.

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

public class MySQLJdbcExample {

public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "apmsetup";
try {
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();

String sql = "INSERT INTO auto_increment_test_table (name) VALUE ('test')";
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
int autoIncrement = rs.getInt(1);
System.out.println("autoIncrement: " + autoIncrement);
}

sql = "SELECT LAST_INSERT_ID()";
rs = stmt.executeQuery(sql);
if (rs.next()) {
int autoIncrement = rs.getInt(1);
System.out.println("autoIncrement: " + autoIncrement);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
http://devday.tistory.com/304 에서 펌

'JAVA언어' 카테고리의 다른 글

간단한 Enum 사용법  (0) 2011.12.21
quick sort  (0) 2011.12.21
String 컴파일  (0) 2011.08.05
싱글톤 생성법(늦은 생성)  (0) 2011.04.27
exepiton message printStackTrace처럼 찍기  (0) 2011.04.16
posted by 천상의날개