当前位置:K88软件开发文章中心编程语言JavaSpring → 文章内容

Spring JDBC 示例

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-15 16:21:04

下是 MainApp.java 文件的内容:package com.tutorialspoint;import java.util.List;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.tutorialspoint.StudentJDBCTemplate;public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate"); System.out.println("------Records Creation--------" ); studentJDBCTemplate.create("Zara", 11); studentJDBCTemplate.create("Nuha", 2); studentJDBCTemplate.create("Ayan", 15); 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()); } System.out.println("----Updating Record with ID = 2 -----" ); studentJDBCTemplate.update(2, 20); System.out.println("----Listing Record with ID = 2 -----" ); Student student = studentJDBCTemplate.getStudent(2); System.out.print("ID : " + student.getId() ); System.out.print(", Name : " + student.getName() ); System.out.println(", Age : " + student.getAge()); }}下述是配置文件 Beans.xml 的内容:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> <!-- Initialization for data source --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/TEST"/> <property name="username" value="root"/> <property name="password" value="password"/> </bean> <!-- Definition for studentJDBCTemplate bean --> <bean id="studentJDBCTemplate" class="com.tutorialspoint.StudentJDBCTemplate"> <property name="dataSource" ref="dataSource" /> </bean></beans>当你完成创建源和 bean 配置文件后,运行应用程序。如果你的应用程序一切运行顺利的话,将会输出如下所示的消息:------Records Creation--------Created Record Name = Zara Age = 11Created Record Name = Nuha Age = 2Created Record Name = Ayan Age = 15------Listing Multiple Records--------ID : 1, Name : Zara, Age : 11ID : 2, Name : Nuha, Age : 2ID : 3, Name : Ayan, Age : 15----Updating Record with ID = 2 -----Updated Record with ID = 2----Listing Record with ID = 2 -----ID : 2, Name : Nuha, Age : 20你可以尝试自己删除在我的例子中我没有用到的操作,但是现在你有一个基于 Spring JDBC 框架的工作应用程序,你可以根据你的项目需求来扩展这个框架,添加复杂的功能。还有其他方法来访问你使用 NamedParameterJdbcTemplate 和 SimpleJdbcTemplate 类的数据库,所以如果你有兴趣学习这些类的话,那么你可以查看 Spring 框架的参考手册。

上一页  [1] [2] 


Spring JDBC 示例