- JDBC整合
- applicationContext.xml
- 代码
- JDBC模板类
- 配置文件
- 代码
- Map
- List
- 使用BeanPropertyRowMapper自动进行映射
代码
package cn.tedu.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test01 {
@Test
public void test01(){
//容器初始化
ApplicationContext context=new
ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean---获取数据源
DataSource source = (DataSource) context.getBean("dataSource");
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn=source.getConnection();
ps = conn.prepareStatement("select * from user where id ");
ps.setInt(1,3);
rs = ps.executeQuery();
while (rs.next()){
System.out.println(rs.getString("name"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
if(rs!=null)
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
rs=null;
}
if(ps!=null)
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
ps=null;
}
if(conn!=null)
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
conn=null;
}
}
}
}
JDBC模板类
配置文件
代码
package cn.tedu.test;
import cn.tedu.domain.User;
import org.junit.After;
import org.junit.Before;
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 java.util.List;
import java.util.Map;
public class Test01 {
private ApplicationContext context = null;
private JdbcTemplate jdbcTemplate = null;
@Before//比所有的层单元测试方法先执行
public void before() {
//容器初始化
context = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
}
@After//比所有的层单元测试方法后执行
public void after() {
//容器关闭
((ClassPathXmlApplicationContext) context).close();
}
@Test
public void test01() {
jdbcTemplate.update("insert into user values(null ,?,?)", "xxx", 99);
}
@Test
public void test02() {
jdbcTemplate.update("update user set age=? where name=?", 55, "xxx");
}
@Test
public void test03() {
jdbcTemplate.update("delete from user where id=?", 17);
}
@Test
public void test04() {
Map map = jdbcTemplate.queryForMap("select * from user where id=?", 3);
System.out.println(map);
}
@Test
public void test05() {
List
Map
List
使用BeanPropertyRowMapper自动进行映射



