//获取连接池对象
BasicDataSource ds=new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/2021aamybatis");
ds.setUsername("root");
ds.setPassword("123456");
//连接池对象获取连接
BasicDataSource ds=(BasicDataSource) ap.getBean("ds");
//conn获取SQL执行对象
Connection conn = ds.getConnection();
PreparedStatement st = conn.prepareStatement("select * from user");
//执行的SQL语句,将数据传递给st对象
ResultSet rs = st.executeQuery();
//executeQuery将st中的数据进行
while(rs.next()) {
System.out.println(rs.getInt("id")+":"+rs.getString("username"));
}
conn.close();
通过Spring完成数据源
数据源注入
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver"></property>
<property name="url"
value="jdbc:mysql://localhost:3306/2021aamybatis"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>