1
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 says:

"con" variable cannot be resolved to a type.

Why?

jjnguy
  • 136,852
  • 53
  • 295
  • 323
Robert13
  • 21
  • 1
  • 3
  • 6

2 Answers2

2

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
 }
jmj
  • 237,923
  • 42
  • 401
  • 438
2

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:

jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • @Tom, of course I would add a null check, or handle it better in the catch. But this is just for educational purposes. – jjnguy Dec 03 '10 at 18:25
  • @Tom, and in a low level method that is connecting to a database, I would just be throwing the Exceptions anyway. There is probably no good way to handle them at that point. – jjnguy Dec 03 '10 at 18:28
  • You are educating to implicitly NPE in sad cases. – Tom Hawtin - tackline Dec 03 '10 at 18:31