企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
配置文件 ``` <!-- spring jdbc datasource --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="${driver}"></property> <property name="url" value="${url}"></property> <property name="username" value="${uname}"></property> <property name="password" value="${password}"></property> </bean> <!-- spring jdbc template --> <bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> ``` java类实现 ``` import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.neuedu.model.po.Student; @Repository public class StudentDAO { @Autowired private JdbcTemplate jt; public void addStudent() { String sql = "insert into student values(null,?,?,?,?,?,?)"; Object[] args = {"123","feiyy",Date.valueOf("1991-1-1"),"女","计算机",1003}; //执行操作 jt.update(sql, args); } public List<Student> getUsers(Student s) { String sql = "select * from student where stuname = ?"; Object[] args = {s.getStuname()}; return jt.query(sql, args,new RowMapper<Student>(){ @Override public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student s = new Student(); s.setStuno(rs.getLong("stuno")); s.setStuname(rs.getString("stuname")); s.setBirthday(rs.getDate("birthday")); return s; } }); } public Student getUser(long stuno) { String sql = "select * from student where stuno = ?"; Object[] args = {stuno}; return jt.queryForObject(sql, args, new RowMapper<Student>(){ @Override public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student s = new Student(); s.setStuno(rs.getLong("stuno")); s.setStuname(rs.getString("stuname")); s.setBirthday(rs.getDate("birthday")); return s; }}); } } ``` 测试类的实现 ``` public class TestSpringJDBC { @Test public void testUpdate() { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDAO dao = ctx.getBean(StudentDAO.class); dao.addStudent(); } @Test public void testQueryList() { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDAO dao = ctx.getBean(StudentDAO.class); Student condition = new Student(); condition.setStuname("汤姆"); List<Student> students = dao.getUsers(condition); for(Student s: students) { System.out.println(s.getStuno()+"\t"+s.getStuname()+"\t"+s.getBirthday()); } } @Test public void testQueryOne() { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDAO dao = ctx.getBean(StudentDAO.class); Student s = dao.getUser(2019040409999L); System.out.println(s.getStuno()+"\t"+s.getStuname()+"\t"+s.getBirthday()); } } ```