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
Connection variable cannot be resolved
提问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
con
variable is local to try block ,
con
变量是局部的 try 块,
try {
Connection con = DriverManager.getConnection("jdbc:sqlite:db/Freepark.sqlite");
}
You are accessing con
it 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 con
inside of the try
block, but try to use it outside of the block. You should do the following:
问题是您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();
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:
变量的作用域是变量对其有效的代码块。作用域还控制在程序运行时创建和销毁变量的时间。我们必须区分四种变量: