您的位置:首页 > 其它

使用jdbc获取插入数据时的主键的方法

2012-08-20 16:32 471 查看
package org.day02;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.day01.ConnectionUtils;

public class TestPK {
/**
* for Oracle
*
* @throws SQLException
*/
public void addOrder1() throws SQLException {
Connection con = null;
PreparedStatement stmt = null;

try {
con = ConnectionUtils.getConnection();
con.setAutoCommit(false);
// 获取ID
stmt = con.prepareStatement("select my_order_seq.nextval from dual");
ResultSet rs = stmt.executeQuery();
rs.next();
int orderId = rs.getInt(1);
System.out.println(orderId);
stmt.close();

// 插入Order
stmt = con.prepareStatement("insert into my_order values(?,?)");
stmt.setInt(1, orderId);
stmt.setDate(2, new Date(System.currentTimeMillis()));
stmt.executeUpdate();
stmt.close();

// 插入2个Item
stmt = con
.prepareStatement("insert into my_item values(my_item_seq.nextval,?,?)");

stmt.setString(1, "java");
stmt.setInt(2, orderId);
stmt.executeUpdate();

stmt.setString(1, "php");
stmt.setInt(2, orderId);
stmt.executeUpdate();
stmt.close();

con.commit();

} catch (SQLException e) {
e.printStackTrace();
con.rollback();
throw e;
} finally {
if (con != null) {
con.close();
}
}
}

/**
* for MySQL
*
* @throws SQLException
*/
public void addOrder2() throws SQLException {
Connection con = null;
PreparedStatement stmt = null;

try {
con = ConnectionUtils.getConnection();
con.setAutoCommit(false);

// 插入Order
stmt = con.prepareStatement("insert into my_order values(null,?)",
Statement.RETURN_GENERATED_KEYS);
stmt.setDate(1, new Date(System.currentTimeMillis()));
stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
rs.next();
int orderId = rs.getInt(1);
System.out.println(orderId);
stmt.close();

// 插入2个Item
stmt = con.prepareStatement("insert into my_item values(null,?,?)");

stmt.setString(1, "java");
stmt.setInt(2, orderId);
stmt.executeUpdate();

stmt.setString(1, "php");
stmt.setInt(2, orderId);
stmt.executeUpdate();
stmt.close();

con.commit();

} catch (SQLException e) {
e.printStackTrace();
con.rollback();
throw e;
} finally {
if (con != null) {
con.close();
}
}
}

public static void main(String[] args) throws Exception {
TestPK pk = new TestPK();
pk.addOrder2();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐