无法解析连接变量

时间:2010-12-03 17:22:03

标签: java variables scope

public class GestorBase{

 public static void main(String[] args){
  try
  {
   Class.forName("org.sqlite.JDBC");
  }
  catch (ClassNotFoundException e) {
   System.out.println("Unable to load driver class");
   // TODO: handle exception
  }
  try {
   Connection con = DriverManager.getConnection("jdbc:sqlite:db/Freepark.sqlite");
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   System.out.println("error al buscar la base de datos");
  }

  Statement sentencia = con.createStatement();


 }}

Eclipse说:

  

“con”变量无法解析为某个类型。

为什么?

2 个答案:

答案 0 :(得分:2)

con变量是尝试块的本地变量,

try {
   Connection con = DriverManager.getConnection("jdbc:sqlite:db/Freepark.sqlite");
  }   

您正在访问try区块的con

应该是

Connection con = null;
Statement sentencia = null;
try {
      con = DriverManager.getConnection("jdbc:sqlite:db/Freepark.sqlite");
      sentencia = con.createStatement();
 } catch (SQLException e) {
      // TODO Auto-generated catch block
      System.out.println("error al buscar la base de datos");
 } catch (Exception ex){

     //handle it
 }

答案 1 :(得分:2)

问题是您在con块内声明了try,但尝试在块之外使用它。您应该执行以下操作:

Connection con = null;
try {
   con = DriverManager.getConnection("jdbc:sqlite:db/Freepark.sqlite");
} catch (SQLException e) {
   // TODO Auto-generated catch block
   System.out.println("error al buscar la base de datos");
   return; // return because nothing can be done w/out a connection
}

Statement sentencia = con.createStatement();

导致错误的原因是,一旦执行退出try块,con变量就会超出范围,并且不再可见。

Here is a little info about scope滚动到标题为变量

的第一部分
  

变量的范围是变量有效的代码块。范围还控制何时在程序运行时创建和销毁变量。我们必须区分四种变量: