我如何修复" java.lang.NullPointerException#34;尝试使用数据源连接到mysql时出错

时间:2015-01-19 06:52:32

标签: java mysql jdbc datasource

我与mysql数据库有一个有效的连接:

        public static javax.sql.DataSource getJDBCDataSource() throws    DAOException
          {
         try {
          if (_ds == null)
         {
            _ds = (javax.sql.DataSource) getContext().lookup(
                    CommonUtilities.getServerProperties().getProperty(                         PropertyFileConfigurationKeys.CONFIG_SERVER_MYSQL_JNDI.toString()
                            )
                    );
        }

        return _ds;
    } catch (NamingException ex) {
        throw new DAOException("Problem looking up resource by name; see chained exception.", ex);
    }
}

mySQL数据库的JNDI在persistence.xml中定义。 当我尝试运行查询进行测试时,它会给出一个nullpointer异常:

    try{
        DataSource ds = BeanUtilities.getJDBCDataSource();
        InterviewerProperty ip1 = new InterviewerProperty(ds);
        Collection<EmployeeVO> results = ip1.getEmployees();
        for(EmployeeVO next:results) {
            System.out.println(next);
         }
     }
    catch(DAOException e){
        System.out.println("Exception occured");
        System.out.println(e);
    }
}

getEmployees访问数据库的方法是:

 public ArrayList<EmployeeVO> getEmployees() throws DAOException {
    Connection connection = null;
    PreparedStatement statement = null;
    ArrayList<EmployeeVO> result = new ArrayList<EmployeeVO>();
     try {
        connection = getConnection();
        statement = connection.prepareStatement("select * from employee");
        ResultSet rs = statement.executeQuery();
        while(rs.next()) {
        result.add((EmployeeVO) rs);}
        rs.close();
     } catch (SQLException ex) {
        String err = "Unable to fetch Employees";
        throw new DAOException(err,ex);
     } finally {
        close(statement,connection);
     }
     return result;
}

错误是:

     **Exception in thread "main" java.lang.NullPointerException
       at javax.naming.InitialContext.getURLScheme(InitialContext.java:269)
       at   javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:318)
       at javax.naming.InitialContext.lookup(InitialContext.java:392)
       at  edu.ufl.bebr.scheduler.framework.BeanUtilities.getJDBCDataSource(BeanUtilities.java:57)
       at edu.ufl.bebr.scheduler.ejb3.session.TestRun.main(TestRun.java:44)**

有关如何修复错误的任何帮助都会很棒。 提前谢谢!

0 个答案:

没有答案