为什么这不起作用(抛出异常:)Cannot create JDBC driver of class '' for connect URL 'null'
?
public class Test {
public static BasicDataSource dataSource = new BasicDataSource();
public Test() {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("");
dataSource.setUrl("jdbc:mysql://localhost/database");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");
}
public static void main(String[] args) throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
SqlRowSet rs = jdbcTemplate.queryForRowSet("SELECT * FROM table");
}
}
但这确实有效
public class Test {
public static void main(String[] args) throws Exception {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("");
dataSource.setUrl("jdbc:mysql://localhost/database");
dataSource.setMaxActive(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
SqlRowSet rs = jdbcTemplate.queryForRowSet("SELECT * FROM table");
}
}
为什么我不能在构造函数中启动一次 dataSource 并在整个方法中使用它?