在catch块中找不到连接对象?

时间:2014-03-10 22:38:44

标签: java

我的连接已建立,如下面的代码段所示。我试图在catch块中再次使用相同的连接,如下所示:

Statement InsertRemoteResultsStmt = null;
try {
     Connection connRemote = DriverManager.getConnection("//my urls here");

     // other stuff here
}
catch(SQLException ex)
{
    InsertRemoteResultsStmt = connRemote.createStatement(); // error comes here

}

我在Netbeans "cannot find symbol connRemote"中收到错误消息。我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

Connection connRemote = null;
Statement InsertRemoteResultsStmt = null;
try {
    connRemote = DriverManager.getConnection("//my urls here");
    // other stuff here
}
catch(SQLException ex) {
    InsertRemoteResultsStmt = connRemote.createStatement(); // error comes here
}

但是,您无法确定您的连接对象在catch子句中是否有效。考虑重新组织代码,例如在try子句中嵌套一个额外的try / catch语句。

相关问题