2010-12-03 68 views
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中說:連接變量不能得到解決

「CON」 變量不能被解析爲一個類型。

爲什麼?

回答

2

con變量是本地try塊,

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

你出訪問con它try塊的一側。

應該

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 
} 
+0

然後你得到一個NPE,如果它失敗.... – 2010-12-03 18:01:30

+0

@湯姆霍廷 - 粘線當然,這不是OP問。 – 2010-12-03 18:04:15

2

的問題是,你聲明contry塊內,但嘗試使用它的塊之外。你應該做到以下幾點:因爲,一旦執行退出try塊中,con變量超出範圍,不再可見是造成

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(); 

錯誤。

Here is a little info about scope滾動至第一部分題爲變量

的變量的範圍是代碼塊的量,可變是有效的。範圍還控制程序運行時何時創建和銷燬變量。有四種變量我們必須區分:

相關問題