[英]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 = 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? 为什么?
con
variable is local to try block , con
变量是try到try的本地变量,
try {
Connection con = DriverManager.getConnection("jdbc:sqlite:db/Freepark.sqlite");
}
You are accessing con
it out side of try block. 您正在访问
con
出来try块的一侧。
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
}
The problem is that you declared con
inside of the try
block, but try to use it outside of the block. 问题是你在
try
块中声明了con
,但是尝试在块之外使用它。 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. 导致错误的原因是,一旦执行退出
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:
我们必须区分四种变量:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.