如果把Connection的AutoCommit设为False,两次executeQuery之间,通过其它途径(我通过Navicat)修改了status值为1,第二次executeQuery依然把那条数据读出来了,也就是说,我在Navicat中的操作就像没有发生一样,需要重新连接或者con.commit()一下才能读到。猜测可能是事务的隔离级别造成的。
con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
不允许脏读,果然OK了,这种情况平时还是要注意一下的
- Connection con = DriverManager
- .getConnection(
- "jdbc:mysql://localhost/spider?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true",
- "root", "111111");
- con.setAutoCommit(false);
- Statement stmt = null;
- ResultSet rs = null;
- try {
- stmt = con.createStatement();
- rs = stmt.executeQuery("select * from queue where status="
- + String.valueOf(0));
- while (rs.next()) {
- String url = rs.getString("url");
- System.out.println(url);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- if (stmt != null) {
- try {
- stmt.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- Thread.sleep(15000); //等待的时候在navicat中修改数据的status=1
- System.out.println("next");
- try {
- stmt = con.createStatement();
- rs = stmt.executeQuery("select * from queue where status="
- + String.valueOf(0));
- while (rs.next()) {
- String url = rs.getString("url");
- System.out.println(url);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- if (stmt != null) {
- try {
- stmt.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
本文转自 dogegg250 51CTO博客,原文链接:http://blog.51cto.com/jianshusoft/765736,如需转载请自行联系原作者