java 无法解析连接变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4348103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:00:03  来源:igfitidea点击:

Connection variable cannot be resolved

javavariablesscope

提问by Robert13

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:

Eclipse 说:

"con" variable cannot be resolved to a type.

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

Why?

为什么?

回答by Jigar Joshi

convariable is local to try block ,

con变量是局部的 try 块,

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

You are accessing conit out side of try block.

您正在con尝试块之外访问它。

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
 }

回答by jjnguy

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

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

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 tryblock, the convariable goes out of scope, and is no longer visible.

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

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:

变量的作用域是变量对其有效的代码块。作用域还控制在程序运行时创建和销毁变量的时间。我们必须区分四种变量: