使用JDBCTemplate执行DQL/DML语句

package cn.itcast.datasource.jdbctemplate;

import cn.itcast.domain.User;
import cn.itcast.utils.JDBCUtils;

import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
* @author newcityman
* @date 2019/8/17 - 21:05
*/
public class JdbcTemplateDemo02 {
/*
* 根据id号,修改user对象
* */
// 获取JdbcTemplate对象
private JdbcTemplate temp = new JdbcTemplate(JDBCUtils.getDataSource());

@Test
public void test01() {
// 定义sql
String sql = "update user set name=?,email=?,tel=? where id=?";
// 执行sql语句
int i = temp.update(sql, "light", "[email protected]", "13770578331", 3);
// 判断执行结果
if (i > 0) {
System.out.println("数据修改成功");
} else {
System.out.println("数据修改失败");
}
}

/*
* 添加一条记录
* */
@Test
public void test02() {
// 定义sql
String sql = "insert into user(id,name,email,tel) values(null,?,?,?)";
// 执行sql语句
int i = temp.update(sql, "小猪", "[email protected]", "177025874");
// 判断执行结果
if (i > 0) {
System.out.println("数据添加成功");
} else {
System.out.println("数据添加失败");
}
}

/*
* 删除id=7的记录
* */

@Test
public void test03() {
// 定义sql语句
String sql = "delete from user where id=?";
// 执行sql语句
int i = temp.update(sql, 7);
// 判断执行结果
if (i > 0) {
System.out.println("数据删除成功");
} else {
System.out.println("数据删除失败");
}
}

/*
* 查询指定id的记录,并将其封装为Map集合
* */
@Test
public void test04(){
// 定义sql
String sql="select id,name,email,tel from user where id=?";
Map<String, Object> map = temp.queryForMap(sql, 3);
System.out.println(map);
}

/*
* 查询所有记录,并将其封装为list集合
* */
@Test
public void test05(){
String sql="select * from user";
List<Map<String, Object>> list = temp.queryForList(sql);
for (Map<String, Object> obj : list) {
System.out.println(obj);
}
}

/*
* 查询所有记录,并将其封装为emp对象的集合
* */
@Test
public void test06(){
String sql ="select id ,name ,email ,tel from user ";

List<User> list = temp.query(sql, new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int i) throws SQLException {
User user = new User();
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
String tel = rs.getString("tel");

user.setId(id);
user.setName(name);
user.setEmail(email);
user.setTel(tel);

return user;
}

});
for (User user : list) {
System.out.println(user);
}

}

/*
* 查询所有记录,并将其封装为emp对象的集合
* */
@Test
public void test06_2(){
String sql ="select id ,name ,email ,tel from user ";
List<User> list = temp.query(sql, new BeanPropertyRowMapper<User>(User.class));

for (User user : list) {
System.out.println(user);
}
}

/*
* 查询所有记录数
* */
@Test
public void test07(){
String sql ="select count(id) from user";
Long count = temp.queryForObject(sql, Long.class);
System.out.println(count);
}

}

猜你喜欢

转载自www.cnblogs.com/newcityboy/p/11370872.html