我把程序打成jar包后用dos运行,之前部分都正常,但当运行到用到数据库的部分时候connection.createStatement报错
java.lang.NullPointerException
不打包时运行一切正常,这是怎么回事?

解决方案 »

  1.   


    if(connection == null){
       System.out.println("未建立连接");
    }
    connection.createStatement
      

  2.   

    public static void connect() {
    try{
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";
    String username = "root";
            String password = "root";
        con = DriverManager.getConnection(url , username , password);     
    } catch (SQLException e) {
    } catch (Exception e) {
    }
    }之前已经执行过这个connect()函数了
      

  3.   

    打包的话,得在 MANIFEST.MF 文件中加上 Class-Path: lib/mysql-jdbc-xxx.jar 加上这么一行。然后打包生成 jar 文件,在这个文件的同级目录下建一个 lib 目录,把 mysql-jdbc-xxx.jar 复制进去就行了。由于你把异常信息给吃掉了:} catch (SQLException e) {
    } catch (Exception e) {
    } 所以不会输出错误,这种情况应该会报 ClassNotFoundException 的异常。建议不要吃掉异常,使用 e.printStackTrace(); 便于调试。
      

  4.   

    我这个工程里没有MANIFEST.MF?
      

  5.   

    我之前也遇到过类似的错误
    MANIFEST.MF在打包jar文件时可以生成,我用的是eclipse
      

  6.   

    Eclipse 导出/打包jar文件的方法
      

  7.   

    对了。里面的参考文章也可以看看,熟悉一下jar