Spring框架对jdbc进行封装,使用JdbcTemplate方便实现对数据库操作
1.引入相关依赖
2.配置数据库连接文件
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="jdbc:mysql:///user_db"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" value="dataSource">property>
bean>
4.编写相关类
@Service
public class BookService {
@Autowired
private BookDao bookDao;
}
@Repository
public class BookDaoImpl implements BookDao {
@Autowired
private JdbcTemplate jdbcTemplate;
}
@Override
public void add(Book book) {
//定义sql语句
String sql = "insert into t_book values(?,?,?)";
//调用更新方法,返回受影响的行数
int row = jdbcTemplate.update(sql, book.getUserId(), book.getUsername(), book.getUstatus());
System.out.println("添加成功" + row);
}
//更新方法,args[]表示传入占位符内容
@Override
public void updateBook(Book book) {
//定义sql语句
String sql = "update t_book set username=?,ustatus=? where user_id=? ";
int row = jdbcTemplate.update(sql, book.getUsername(), book.getUstatus(), book.getUserId());
System.out.println("更新成功" + row);
}
@Override
public void deleteBook(int id) {
//定义sql语句
String sql = "delete from t_book where user_id=?";
int row = jdbcTemplate.update(sql, id);
System.out.println("删除成功" + row);
}
查询表里有多少条记录,返回的是某个值
//查询记录数
@Override
public int selectCount() {
String sql = "select count(*) from t_book";
int result = jdbcTemplate.queryForObject(sql, Integer.class);
return result;
}
查询内容详情,返回对象
//查询返回单个对象
@Override
public Book findBookInfo(Integer id) {
String sql = "select * from t_book where user_id=?";
Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
return book;
}
返回集合
//查询返回集合
@Override
public List<Book> findBookList() {
String sql = "select * from t_book";
//返回一个集合对象
List bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
return bookList;
}
批量添加数据(batchUpdate)
//批量添加操作
@Override
public void batchAddBook(List<Object[]> batchArgs) {
String sql = "insert into t_book values(?,?,?)";
int[] rows = jdbcTemplate.batchUpdate(sql, batchArgs);
System.out.println(Arrays.toString(rows));
}
批量修改和批量删除实现过程类似,只是sql语句和传入参数内容不同