JDBC Insert语句插入Oracle数据库返回数据主键
来源:程序员人生 发布时间:2014-12-08 09:04:22 阅读次数:3938次
表结构:
create table test(
id varchar2(32) primary key,
name varchar2(32)
);
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
/**
* 使用Statement.RETURN_GENERATED_KEYS 指定返复生成主键
*/
public static void main(String[] args) {
PreparedStatement pst = null;
ResultSet rs = null;
Connection conn = ConnectionManager.getConnection();
String sql = "insert into test(id,name) values(?,?)";
try {
//String generatedColumns[] = { "ID" }; //取得指定ID
pst = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); // 指定返复生成的主键
pst.setString(1, "123x");
pst.setString(2, "test");
int ii = pst.executeUpdate();
// 检索对象生成的键
rs = pst.getGeneratedKeys();
if (rs.next()) {
System.out.println("数据主键:" + rs.getString(1));
}
ConnectionManager.closeAll(rs, pst, conn); // 关闭资源
} catch (SQLException e) {
e.printStackTrace();
}
}
}
以下是JDBC辅助类,不是本文重点
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectionManager {
public static final String DRIVER = "oracle.jdbc.driver.
OracleDriver";
public static final String URL = "jdbc:oracle:thin:@localhost:1521/orcl";
public static final String USERNAME = "root";
public static final String PASSWORD = "root";
/**
* 通过静态代码块 注册
数据库驱动
*/
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 取得Connection
*
* @return
*/
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
}catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭ResultSet
* @param rs
*/
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭Statement
* @param st
*/
public static void closeStatement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭Connection
* @param conn
*/
public static void closeConnection(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭全部
* @param rs
* @param sta
* @param conn
*/
public static void closeAll(ResultSet rs,Statement sta,Connection conn){
closeConnection(conn);
closeStatement(sta);
closeResultSet(rs);
}
}
控制台打印:
数据主键:AAAT2zAANAAACalAAB
而我们的主键是ID值为123x.那打印的AAAT2zAANAAACalAAB是甚么玩意呢,使用rs.getObject(1)在控制台打印,显示以下:
数据主键:oracle.sql.ROWID@452bb7e0
实际上是test表的ROWID字段值
如果要取得指定的ID字段值 可以用以下方法:
String generatedColumns[] = { "ID" };
pst = conn.prepareStatement(sql, generatedColumns);
作者:itmyhome出处:http://blog.csdn.net/itmyhome1990/article/details/41600309
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠