在Sping中使用数据源需要导入两个架包commons-pool-1.4.jar与commons-dbcp-1.2.1.jar
使用数据源可以通过两种方式:1、第一种完全使用xml文件配置2、使用properties文件与xml文件配置
一、完全使用xml文件进行配置
applicationContext.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hibernate"/>
<property name="username" value="root"></property>
<property name="password" value="7756"></property>
</bean>
二、使用properties文件与xml文件配置
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hibernate
jdbc.username=root
jdbc.password=7756
applicationcontext.xml
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
StudentsDAOImpl.java
package com.spr.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.stereotype.Component;
import com.spr.vo.Students;
@Component("studentsDAOImpl")
public class StudentsDAOImpl implements StudentsDAO{
@Resource
private DataSource dataSource;
@Override
public boolean saveStudents(Students s) {
// TODO Auto-generated method stub
if(s != null){
String sql = "insert into students values (?,?)";
try {
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, s.getSid());
statement.setString(2, s.getSname());
statement.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
else{
return false;
}
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}