开发者

Connection variable cannot be resolved

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 = Drive开发者_如何转开发rManager.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 says:

"con" variable cannot be resolved to a type.

Why?


con variable is local to try block ,

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

You are accessing con it out side of try block.

It should be

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
 }
  • Have a look at variable scope and blocks


The problem is that you declared con inside of the try block, but try to use it outside of the block. You should do the following:

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();

The error was caused because that once the execution exits the try block, the con variable goes out of scope, and is no longer visible.

Here is a little info about scope: scroll to the first section entitled Variables

The variable's scope is the block of code for which the variable is valid. Scope also controls when the variable is created and destroyed as the program runs. There are four kinds of variables we must distinguish:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜