Why do we use a DataSource instead of a DriverManager?

前端 未结 5 484
栀梦
栀梦 2020-12-07 07:39

I am reading the Java JDBC specification (vr. 4) and I encountred this statement:

DataSource — this interface was introduced in the JDBC 2.0 Optional

5条回答
  •  执念已碎
    2020-12-07 08:08

    Below code shows two way for getting connection.

    There is no need to know about URL in case of mySqlDataSource as this line is commented.

    public class MySqlDataSourceTest {
    
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    
    
        /************** using MysqlDataSource starts **************/
        MysqlDataSource d = new MysqlDataSource();
        d.setUser("root");
        d.setPassword("root");
    //  d.setUrl("jdbc:mysql://localhost:3306/manavrachna");
        d.setDatabaseName("manavrachna");
        Connection c =  (Connection) d.getConnection();
        /************** using MysqlDataSource ends**************/
    
    
        /************** using DriverManager start **************/
        Class.forName("com.mysql.jdbc.Driver");
        Connection c=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/manavrachna","root","root");
        /************** using DriverManager ends **************/
    
        Statement st=(Statement) c.createStatement();
        ResultSet rs=st.executeQuery("select id from employee");
        while(rs.next())
        {
            System.out.println(rs.getInt(1));
        }
    
    }
    
    }
    

提交回复
热议问题