Spring JDBC查询数据

以下示例将展示如何使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值