/** |
* |
* 这是插入一条数据的同时,获取该数据的则增长列的值(该例子的自增长列是id) |
* |
* @author LZL |
* |
*/ |
public class Auto_Increment { |
private static Connection conn = null ; |
private static PreparedStatement pstsm = null ; |
private static ResultSet rs = null ; |
@Test |
public void testGetAutoIncrement() { |
try { |
// 1:创建连接 |
conn = Jdbcutil.getConnection(); |
// 2:设置sql预编译语句 |
String sql = "INSERT INTO person (NAME,sex,age) VALUES (?,?,?);" ; |
// 3:执行sql预编译语句(同时在参数中指定自增列) |
pstsm = conn.prepareStatement(sql, |
PreparedStatement.RETURN_GENERATED_KEYS); |
// 4:设置参数值 |
pstsm.setString( 1 , "王五" ); |
pstsm.setString( 2 , "男" ); |
pstsm.setInt( 3 , 22 ); |
// 5:发送参数,执行sql |
pstsm.executeUpdate(); |
// 6:执行完上面的更新数据操作后,获取自增长列 |
rs = pstsm.getGeneratedKeys(); |
// 7:输出该数据对应的自增长列的值 |
if (rs.next()) { |
System.out.println( "刚才添加的数据的自增长列值是:" + rs.getInt( 1 )); |
} |
} catch (Exception e) { |
e.printStackTrace(); |
throw new RuntimeException(e); |
} finally { |
} |
Jdbcutil.close(conn, pstsm, rs); |
} |
} |
中级程序员
by: 时间可以改变一切 发表于:2016-12-21 18:40:47 顶(0) | 踩(0) 回复
Connection conn = DB.getConnection();
boolean b = conn.getAutoCommit();
int id = -1;
conn.setAutoCommit(false);
//System.out.println(b);
//System.out.println(id);
//System.out.println(rootid);
//System.out.println(title);
//System.out.println(cont);
String sql = "insert into article values(null, 0, ?, ?, ?, now(), 0)";
PreparedStatement pstmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); // 获取自动增长值
pstmt.setInt(1, id);
pstmt.setString(2, title);
pstmt.setString(3, cont);
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
id = rs.getInt(1);
//System.out.println(rs.getInt(1));
Statement stmt = DB.getStatement(conn);
stmt.executeUpdate("update article set rootid =" + id + "where id =" + id);
conn.commit();
回复评论