入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

Spring JDBC查询数据

创建时间:2018-03-07 投稿人: 浏览次数:213

以下示例将展示如何使用Spring jdbc进行查询数据记录,将从student表中查询记录。

语法:

String selectQuery = "select * from student";
List <Student> students = jdbcTemplateObject.query(selectQuery, new StudentMapper());

在上面语法中 -

  • selectQuery - 选择查询学生数据记录。
  • jdbcTemplateObject - StudentJDBCTemplate 对象将 Student 对象插入到数据库中。
  • StudentMapper - StudentMapper是一个RowMapper对象,用于将每个获取的记录映射到Student对象。

查询数据方法

public List<Student> listStudents() {
		String sql = "select * from student";
		List<Student> students = jdbcTemplateObject.query(sql, new StudentMapper());
		return students;
	}


执行程序:

public class MainApp {

	public static void main(String[] args) {

		ApplicationContext context = new ClassPathXmlApplicationContext("application-beans.xml");

		StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate) context.getBean("studentJDBCTemplate");

		 System.out.println("------Listing Multiple Records--------");
		 List<Student> students = studentJDBCTemplate.listStudents();
		 for (Student record : students) {
		 System.out.print("ID : " + record.getId());
		 System.out.print(",Name : " + record.getName());
		 System.out.println(",Age : " + record.getAge());
		 }
	}
}

输出结果:

ID : 10,Name : Allen,Age : 17
ID : 11,Name : Ray,Age : 18
ID : 12,Name : Mark,Age : 20
ID : 13,Name : Allen,Age : 17
ID : 14,Name : Ray,Age : 18
ID : 15,Name : Mark,Age : 20
ID : 16,Name : Allen,Age : 17
ID : 17,Name : Ray,Age : 18
ID : 18,Name : Mark,Age : 20
ID : 19,Name : Allen,Age : 17
ID : 20,Name : Ray,Age : 18
ID : 21,Name : Mark,Age : 20

阅读更多
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。