测试 package testSpring;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import test.spring.model.User;
public class TestSpring {
@Test
public void testUser() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate= ac.getBean(JdbcTemplate.class);
/* 增加 */
String sql1="insert into 'users' ('userName','password') values (?,?) ";
jdbcTemplate.update(sql1, "abc","abc123");
/* 删除 */
String sql2="delete from 'users' where id=? ";
jdbcTemplate.update(sql2, 1);
/* 查找一个对象 */
String sql3 = "select * from User where id=?";
RowMapper< User> mapper=new BeanPropertyRowMapper<>(User.class);
User user=jdbcTemplate.queryForObject(sql3, mapper, 1);
System.out.println(user);
/* 查找出多个数据 */
String sql4 = "select * from User where id>?";
RowMapper< User> mapper2=new BeanPropertyRowMapper<>(User.class);
List<User> users =jdbcTemplate.query(sql4, mapper2, 0);
System.out.println(users);
/* 查找显示单个列值 */
String sql5 = "select count(id) from users";
Long count=jdbcTemplate.queryForObject(sql5, Long.class);
System.out.println(count);
/*批量插入*/
String sql7="insert into 'users' ('userName','password') values (?,?) ";
List<Object[]> args=new ArrayList<>();
args.add(new Object[] {"aa","aa123"});
args.add(new Object[] {"bb","bb123"});
jdbcTemplate.batchUpdate(sql7, args);
}
}