gpt4 book ai didi

java - 来自 CachedRowSet 的连接

转载 作者:行者123 更新时间:2023-11-30 03:39:28 27 4
gpt4 key购买 nike

我有以下 Java 7 代码来创建 CachedRowSet

CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet(); 

有没有办法从CachedRowSet对象获取Connection对象?我想在调用 CachedRowSet 上的 acceptChanges() 之前在 Connection 对象上将 autoCommit 设置为 false,因为当我遇到以下异常时调用acceptChanges()

javax.sql.rowset.spi.SyncProviderException: Can't call commit when autocommit=true

CachedRowSet 上有一个 COMMIT_ON_ACCEPT_CHANGES 字段,但已弃用。

最佳答案

嗯,我花了一些时间才重现这个问题。通过 conn.setAutoCommit(false);ConnectionautoCommit 值设置为 false 解决了此问题。

以下是示例工作程序:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;

public class CRSetChecker {
public static void main(String[] args) {
String connectString = "jdbc:oracle:thin:scott/tiger" +
"@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)" +
"(HOST=myorahost)(PORT=5521))" +
"(CONNECT_DATA=(SID=myorasid)))";

//Get DB connection
Connection conn = (new CRSet()).getConnection(connectString);
if (conn == null) {
System.out.println("Connection failed");

System.exit(0);
} else {
System.out.println("Connection established successfully!");

try {
CachedRowSet crs =
RowSetProvider.newFactory().createCachedRowSet();
String query="select ename from emp";
crs.setCommand(query);
crs.execute(conn);
//Set auto commit false
conn.setAutoCommit(false);
int count = 0;
while(crs.next()){
String name = crs.getString(1);
count++;
System.out.println(name);
if(count==1){
crs.updateString(1, "COOPER");
crs.updateRow();
crs.acceptChanges(conn);
System.out.println("After update:"+crs.getString(1));
}
}
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}

public Connection getConnection(String connectString)
{
Connection con = null;
try {
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

con = DriverManager.getConnection(connectString);
} catch (SQLException ex) {
ex.printStackTrace();
}

return con;
}
}

关于java - 来自 CachedRowSet 的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27097537/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com