Why is QueryRunner runner null in my code?
I am a beginner in java programming. I am trying to develop a program but when I ran my program which is posted below and it came back with this error
Exception in thread "main" java.lang.NullPointerException
at Dao.GoodsImp.getByName(GoodsImp.java:94)
at Dao.GoodsImp.main(GoodsImp.java:119)
public class GoodsImp implements GoodsDao{
private static Connection conn;
private static QueryRunner runner;
@BeforeClass
public static void bc() throws SQLException {
conn = myDBUtils.getConnection();
runner = new QueryRunner();
}
@AfterClass
public static void ac() throws SQLException {
if (conn != null && !conn.isClosed())
conn.close();
}
@Override
public List<User> getByName(String name) throws SQLException {
/*String sql = "select * from goods where name like ?";
List<Goods> list = runner.query(conn, sql, new BeanListHandler<>(Goods.class), name);
for (Goods goods : list) {
System.out.println(goods);
}
return list;*/
String sql = "select * from user where name like ?";
List<User> list = runner.query(conn, sql, new BeanListHandler<>(User.class), name);
return list;
}
public static void main(String[] args) throws SQLException {
GoodsImp gd = new GoodsImp();
List<User> list = new ArrayList<>();
list = gd.getByName("zhangsan");
for (User user : list) {
System.out.println(user);
}
}
}
Advertisement
Answer
You’re mixing test systems (that’s what @BeforeClass and @AfterClass are about) and actual apps.
Essentially: @BeforeClass and @AfterClass are just ‘markers’. They do nothing at all on their own; other software interacts with them. Specifically, junit. Which you aren’t running here, so they do nothing.
Move the initialization code to your main method. (for example, invoke bc() there).