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”变量无法解析为某个类型。
为什么?
答案 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:滚动到标题为变量
的第一部分变量的范围是变量有效的代码块。范围还控制何时在程序运行时创建和销毁变量。我们必须区分四种变量: