0

これが機能しないのはなぜですか (例外をスローします: 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 を一度開始して、メソッド全体で使用できないのはなぜですか?

4

1 に答える 1