繁体   English   中英

尝试访问数据库时导致NullPointerException

[英]NullPointerException resulting when attempting to access database

这是给我NullPointerException 我将其范围缩小到查询数据库的行。

该代码未到达第二个记录器。 在异常输出之前将其抛出。

更新:我刚刚测试了jdbcTemplate,它是NULL。

public boolean usernameVerificationProcessService(String string){
    HomeController.logger.info("In method usernameVerificationProcessService in UIDao.");
    HomeController.logger.info("Attention: " + string);
    boolean result = false;
    String sql = "select count(*) from users where username = ?";
    int count = this.jdbcTemplate.queryForObject(sql, new Object[]{string}, java.lang.Integer.class);
    HomeController.logger.info("Attention: " + count);
    if(count == 0) {
        result = true;
    }
    return result;
}

这是配置文件的描述。 我正在使用BasicDataSource和MySQL。

<beans:bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <beans:property name="url" value="jdbc:mysql://localhost:3306"/>
    <beans:property name="username" value="test"/>
    <beans:property name="password" value="test"/>
    <beans:property name="initialSize" value="2" />
    <beans:property name="maxActive" value="5" />
</beans:bean>

您是否忘记将jdbcTemplate注入对象?

public class DBaseAccess {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
  .......
}

您必须将jdbcTemplate注入到spring配置文件(applicationContext.xml)中的对象

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource" />
 </bean>
 <bean id="dBaseAccess" class="coc.taf.dbase.DBaseAccess">
    <property name="jdbcTemplate" ref="jdbcTemplate" />
 </bean>

您永远不会检查string参数是否为null 我想NPE失败了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM