Created
August 3, 2012 02:57
-
-
Save seraphy/3243901 to your computer and use it in GitHub Desktop.
JDBCで、OracleのINSERT文でシーケンスでプライマリキーを採番したときのプライマリキーの取得方法
This file contains 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
package oracleinstest; | |
import java.sql.*; | |
import oracle.jdbc.pool.OracleDataSource; | |
public class OracleInsTest { | |
/** | |
* OracleのINSERT文でプライマリキーとしてシーケンスオブジェクトを使ったとき、 | |
* 生成されたキーの値をgetGeneratedKeysメソッドで取得するための方法. | |
* Oracleg11g/XE + ojdbc6.jar (JDBC4) + JDK7 | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) throws SQLException { | |
OracleDataSource ds = new OracleDataSource(); | |
ds.setURL("jdbc:oracle:thin:@localhost:1521/XE"); | |
ds.setUser("testuser"); | |
ds.setPassword("testuser"); | |
// INSERT文でプライマリキーの生成としてシーケンスオブジェクトを使う. | |
String sql = "insert into testtbl(idx, val, nval) values (testtbl_seq.nextval, ?, ?)"; | |
int suffix = (int)(System.currentTimeMillis() % 100); | |
// カラム名を明示する場合 | |
try (Connection conn = ds.getConnection(); | |
// Oracleで getGeneratedKeys を使うには、戻り値となるカラム名を予め明示しておく | |
// http://otndnld.oracle.co.jp/document/products/oracle10g/102/doc_cd/java.102/B19275-03/jdbcvers.htm | |
PreparedStatement stm = conn.prepareStatement(sql, new String[] {"idx"})) { | |
stm.setString(1, "hello, " + suffix); | |
stm.setString(2, "日本語大丈夫? " + suffix); // ojdbc6ならsetFormOfUseは不要 | |
int ret = stm.executeUpdate(); | |
System.out.println("result=" + ret); | |
try (ResultSet rs = stm.getGeneratedKeys()) { | |
if (rs.next()) { | |
int idx = rs.getInt(1); | |
System.out.println("idx(generated)=" + idx); | |
} | |
} | |
} | |
// ROWIDの場合 | |
try (Connection conn = ds.getConnection(); | |
// RETURN_GENERATED_KEYSを指定するとOracleの場合はROWIDが返る. (列を特定できないため) | |
PreparedStatement stm = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { | |
stm.setString(1, "hello, " + suffix); | |
stm.setString(2, "日本語大丈夫? " + suffix); // ojdbc6ならsetFormOfUseは不要 | |
int ret = stm.executeUpdate(); | |
System.out.println("result=" + ret); | |
try (ResultSet rs = stm.getGeneratedKeys()) { | |
if (rs.next()) { | |
String rowid = rs.getString(1); | |
System.out.println("rowid(generated)=" + rowid); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment