1.在配置文件中的配置:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql:///struts" />
<property name="properties">
<props>
<prop key="user">root</prop>
<prop key="password">root</prop>
</props>
</property>
</bean>
<bean id="simpleJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<bean id="userSimpleJdbcTemplateDao" class="com.yjw.dao.UserSimpleJdbcTemplateDao">
<property name="simpleJdbcTemplate" ref="simpleJdbcTemplate"></property>
</bean>
2.dao中的写法:
package com.yjw.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import com.yjw.bean.User;
public class UserSimpleJdbcTemplateDao {
private SimpleJdbcTemplate simpleJdbcTemplate;
public void setSimpleJdbcTemplate(SimpleJdbcTemplate simpleJdbcTemplate) {
this.simpleJdbcTemplate = simpleJdbcTemplate;
}
public void save(User user){
String sql = "INSERT INTO t_user (username,PASSWORD) VALUES (?,?)";
simpleJdbcTemplate.update(sql, user.getUsername(),user.getPassword());
}
public void update(User user){
String sql = "UPDATE t_user SET username=:username ,PASSWORD=:password WHERE id=:id?";
simpleJdbcTemplate.update(sql, user.getUsername(),user.getPassword(),user.getId());
}
public void delete(int id){
String sql = "delete from t_user where id=?";
simpleJdbcTemplate.update(sql, id);
}
private class UserRowmapper implements RowMapper<User> {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User u = new User();
u.setId(rs.getInt("id"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
return u;
}
}
public User getUser(int id) {
String sql = "select id,username,password from t_user where id=?";
User user = simpleJdbcTemplate.queryForObject(sql, new UserRowmapper(), id);
return user;
}
public List<User> getList(){
String sql = "select id,username,password from t_user ";
List<User> list = simpleJdbcTemplate.query(sql, new UserRowmapper() );
return list;
}
}