1:让RS成为可以前后移动的 @Test public void test() throws Exception { // 在创建St对象时,可以指定查询的rs是否可以滚动 Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = st.executeQuery("select * from person"); // 直接移动到行尾 rs.afterLast(); // 前移动 while (rs.previous()) { String name = rs.getString("name"); System.err.println(name); } System.err.println("-----此时游标的位置是:行首--------"); while (rs.next()) { String name = rs.getString("name"); System.err.println(name); } System.err.println("-------------------------"); rs.absolute(1); System.err.println(rs.getString("name"));// Jack rs.relative(1); System.err.println(rs.getString("name"));// Mary rs.relative(-1); System.err.println(rs.getString("name"));
}
2:滚动的类型 @Test public void test() throws Exception { // 在创建St对象时,可以指定查询的rs是否可以滚动 Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = st.executeQuery("select * from person");
、
3:事务 Connectioin
1:Java代码中的Connection对象控制事务,默认的保要是ST对象执行了SQL语句 就会直接提交。 @Test public void testTx() throws Exception{ System.err.println(con.getAutoCommit());//true }
2:没有事务的情况 @Test public void testTx() throws Exception{ Statement st = con.createStatement(); st.execute("insert into person(id,name) values(301,'Helen')"); st.execute("insert into person(id,name) values(302,'Robot)"); con.close(); }
3:控制事务的代码 1:设置connection的autoCommit为false.不自动提交。 2:处理SQL语句 ,在成功以后,调用connection.commit();手工控制提交. 3:如果出错的回滚数据 connectioin.rollback(): 4:在执行完成后,将connection设置为自动提交。且关闭连接。
@Test
public void testTx() throws Exception {
try {
con.setAutoCommit(false);//开始事务
Statement st = con.createStatement();
st.execute("insert into person(id,name) values(301,'Helen')");
st.execute("insert into person(id,name) values(302,'Robot')");
//提交数据
con.commit();
System.err.println("提交了");
} catch (Exception e) {
System.err.println("出错了回滚..");
con.rollback();
throw e;
}finally {
con.setAutoCommit(true);
con.close();
}
}