[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[备忘]postgresql使用setFetchSize的注意事项

上一篇:[备忘]postgreSQL,事务中查询报错影响commit的问题
下一篇:[备忘]TCP 粘包和拆包的大概方法

添加日期:2021/2/18 18:47:05 快速返回   返回列表 阅读815次
官网说明:
https://jdbc.postgresql.org/documentation/head/query.html#query-with-cursor
网友:
https://www.jianshu.com/p/998099e364b2

注意事项:
The connection to the server must be using the V3 protocol. This is the default for (and is only supported by) server versions 7.4 and later.
The Connection must not be in autocommit mode. The backend closes cursors at the end of transactions, so in autocommit mode the backend will have closed the cursor before anything can be fetched from it.
The Statement must be created with a ResultSet type of ResultSet.TYPE_FORWARD_ONLY. This is the default, so no code will need to be rewritten to take advantage of this, but it also means that you cannot scroll backwards or otherwise jump around in the ResultSet.
The query given must be a single statement, not multiple statements strung together with semicolons.

数据库必须使用V3协议,即pg7.4+
connection的autoCommit必须为false,因为开启autoCommit的话,查询完成cursor会被关闭,那么下次就不能再fetch了。
另外ResultSet必须是ResultSet.TYPE_FORWARD_ONLY类型,这个是默认的。也就是说无法向后滚动。
查询语句必须是单条,不能是用分号组成的多条查询

不过我觉得,用完应该把autoCommit改回来?现在都是连接池,不弄回来,会影响后面程序使用吧?
另外,autoCommit设置为false,会自动commit之前的事务?这里需要测试下,是否有影响。


// make sure autocommit is off
conn.setAutoCommit(false);
Statement st = conn.createStatement();

// Turn use of the cursor on.
st.setFetchSize(50);
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next())
{
    System.out.print("a row was returned.");
}
rs.close();

// Turn the cursor off.
st.setFetchSize(0);
rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next())
{
    System.out.print("many rows were returned.");
}
rs.close();

// Close the statement.
st.close();


-------------------------------
【JDBC在事务操作的细节处理上】

     1、开启BEGIN后,若执行一个报错的SQL语句,则必须在同一个会话中执行END语句才可以继续使用当前的connection会话,否则执行任何语句都会报错。当然在JDBC上的处理时隐式的,这一点请看第二点:

     2、JDBC执行setAutocommit(false)时,会先向数据库发送一个COMMIT提交掉上一个事务,JDBC客户端会设置一个事务待提交状态。并且如果处于该状态时,通过该连接第1个SQL语句时,会先执行BEGIN语句操作,如果要在执行某SQL报错时,要继续执行其他SQL必须执行以下几个动作之一:

        2.1.通过JDBC执行END。

        2.2.通过JDBC执行COMMIT或调用connection.commit()方法,在这个方法内部会自动做这样的动作,并且将JDBC客户端的状态设置为事务空闲状态;

        2.3.通过JDBC执行ROLLBACK或调用connection.rollback();方法。解释同上。

        2.4.connection.setAutocommit(false);再设置一次也会将事务状态处理,上文有解释,它会自动发起一次COMMIT操作。但一定是设置false才会生效发生这个动作。
 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved