2011-12-14 33 views
0

我试图在Eclipse中将Java项目保存为jar文件。无法从.jar文件连接到数据库

由于我正在使用Access数据库,我应该导出所有内容,因此我决定将数据库文件包含在与Main.classSingletonConnection.class(这是管理与数据库的连接的类)的文件夹中。

因此,代码为:

private SingletonConnection()throws ConnessioneException{ 

    idConnection = "root"; 
    passConnection = ""; 

    String slash="\\"; 
    String path=this.getClass().getResource("").getPath().replaceFirst("^.*:", "").replaceFirst("!.*$", "").replace("/", slash.concat("\\")); 

    System.out.println("path è "+path); 

    driverConnection = "sun.jdbc.odbc.JdbcOdbcDriver"; 
    stringConnection = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=C:"+path+"eventi.mdb"; 


    try { 
     Class.forName(driverConnection); 
     conn = DriverManager.getConnection(stringConnection,idConnection,passConnection); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     throw new ConnessioneException(); 
    } 
} 

public static Connection getInstance()throws ConnessioneException{ 
    if(conn==null) 
     new SingletonConnection(); 

    return conn; 
} 

在Eclipse中一切正常。该项目工作并没有例外,但是当我尝试将项目导出为Runnable Jar File或Jar File时,它始终返回ConnessioneException =null,因此与db的连接失败。

的例外是在该方法中的getInstance给定,线“新SingletonConnection()”

我需要在其他PC运行该程序,所以我需要解决。我无法继续使用Eclipse。

+2

什么是堆栈跟踪?是包含在jar文件中的ODBC驱动程序? – Thilo 2011-12-14 11:15:28

回答

0

解决:也许它可以成为有用的人:

*** import org.apache.commons.io.IOUtils; !! (package: commons-io-2.1.jar) 

    idConnection = "root"; 
    passConnection = ""; 

    String slash="\\"; 
    String path=null; 

    String temp=System.getProperty("java.io.tmpdir"); 
    if (!(temp.endsWith("/") || temp.endsWith("\\"))) 
      temp = temp + System.getProperty("file.separator"); 
    File tempDir = new File(temp); 
    File temporaryFile = new File(tempDir, "templateCopy.mdw"); 
    InputStream templateStream = getClass().getResourceAsStream("eventi.mdw"); 
    try { 
     IOUtils.copy(templateStream, new FileOutputStream(temporaryFile)); 

    } catch (FileNotFoundException e1) { 
     e1.printStackTrace(); 
     //Dialog d1=new Dialog("filenotfound"); 
    } catch (IOException e1) { 
     e1.printStackTrace(); 
     //Dialog d2=new Dialog("io"); 
    }catch (Exception e1){ 
     //Dialog d3=new Dialog("general"); 
    } 

    path = temporaryFile.getAbsolutePath(); 

    driverConnection = "sun.jdbc.odbc.JdbcOdbcDriver"; 
    stringConnection = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+path; 


    try { 
     Class.forName(driverConnection); 
     conn = DriverManager.getConnection(stringConnection,idConnection,passConnection); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     throw new ConnessioneException(e.getStackTrace()); 
    }