javascript
jdbc java例子_Spring JDBC 例子
要了解有關Spring JDBC框架與JdbcTemplate類的概念,讓我們寫這將實現所有在下面Student表的CRUD操作的簡單例子。
CREATE TABLEStudent(ID INT NOT NULL AUTO_INCREMENT,NAME VARCHAR(20)NOT NULL,AGE INT NOT NULL,PRIMARY KEY(ID));
在開始之前,讓我們使用Eclipse IDE,并按照下面的步驟來創建一個Spring應用程序:
步驟
描述
1
Create a project with a name?SpringExample?and create a package?com.yiibai?under the?src?folder in the created project.
2
Add required Spring libraries using?Add External JARs?option as explained in the?Spring Hello World Example?chapter.
3
Add Spring JDBC specific latest libraries?mysql-connector-java.jar,org.springframework.jdbc.jar?and?org.springframework.transaction.jar?in the project. You can download required libraries if you do not have them already.
4
Create DAO interface?StudentDAO?and list down all the required methods. Though it is not required and you can directly write?StudentJDBCTemplate?class, but as a good practice, let's do it.
5
Create other required Java classes?Student,?StudentMapper,?StudentJDBCTemplate?andMainApp?under the?com.yiibai?package.
6
Make sure you already created?Student?table in TEST database. Also make sure your MySQL server is working fine and you have read/write access on the database using the give username and password.
7
Create Beans configuration file?Beans.xml?under the?src?folder.
8
The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.
以下是數據訪問對象接口文件StudentDAO.java的內容:
packagecom.yiibai;importjava.util.List;importjavax.sql.DataSource;publicinterfaceStudentDAO{/**
* This is the method to be used to initialize
* database resources ie. connection.
*/publicvoidsetDataSource(DataSourceds);/**
* This is the method to be used to create
* a record in the Student table.
*/publicvoidcreate(Stringname,Integerage);/**
* This is the method to be used to list down
* a record from the Student table corresponding
* to a passed student id.
*/publicStudentgetStudent(Integerid);/**
* This is the method to be used to list down
* all the records from the Student table.
*/publicListlistStudents();/**
* This is the method to be used to delete
* a record from the Student table corresponding
* to a passed student id.
*/publicvoiddelete(Integerid);/**
* This is the method to be used to update
* a record into the Student table.
*/publicvoidupdate(Integerid,Integerage);}
以下是Student.java文件的內容:
packagecom.yiibai;publicclassStudent{privateIntegerage;privateStringname;privateIntegerid;publicvoidsetAge(Integerage){this.age=age;}publicIntegergetAge(){returnage;}publicvoidsetName(Stringname){this.name=name;}publicStringgetName(){returnname;}publicvoidsetId(Integerid){this.id=id;}publicIntegergetId(){returnid;}}
以下是StudentMapper.java文件的內容:
packagecom.yiibai;importjava.sql.ResultSet;importjava.sql.SQLException;importorg.springframework.jdbc.core.RowMapper;publicclassStudentMapperimplementsRowMapper{publicStudentmapRow(ResultSetrs,introwNum)throwsSQLException{Studentstudent=newStudent();student.setId(rs.getInt("id"));student.setName(rs.getString("name"));student.setAge(rs.getInt("age"));returnstudent;}}
下面是實現類文件StudentJDBCTemplate.java 定義DAO接口StudentDAO:
packagecom.yiibai;importjava.util.List;importjavax.sql.DataSource;importorg.springframework.jdbc.core.JdbcTemplate;publicclassStudentJDBCTemplateimplementsStudentDAO{privateDataSourcedataSource;privateJdbcTemplatejdbcTemplateObject;publicvoidsetDataSource(DataSourcedataSource){this.dataSource=dataSource;this.jdbcTemplateObject=newJdbcTemplate(dataSource);}publicvoidcreate(Stringname,Integerage){StringSQL="insert into Student (name, age) values (?, ?)";jdbcTemplateObject.update(SQL,name,age);System.out.println("Created Record Name = "+name+" Age = "+age);return;}publicStudentgetStudent(Integerid){StringSQL="select * from Student where id = ?";Studentstudent=jdbcTemplateObject.queryForObject(SQL,newObject[]{id},newStudentMapper());returnstudent;}publicListlistStudents(){StringSQL="select * from Student";Liststudents=jdbcTemplateObject.query(SQL,newStudentMapper());returnstudents;}publicvoiddelete(Integerid){StringSQL="delete from Student where id = ?";jdbcTemplateObject.update(SQL,id);System.out.println("Deleted Record with ID = "+id);return;}publicvoidupdate(Integerid,Integerage){StringSQL="update Student set age = ? where id = ?";jdbcTemplateObject.update(SQL,age,id);System.out.println("Updated Record with ID = "+id);return;}}
以下是MainApp.java文件的內容:
packagecom.yiibai;importjava.util.List;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importcom.yiibai.StudentJDBCTemplate;publicclassMainApp{publicstaticvoidmain(String[]args){ApplicationContextcontext=newClassPathXmlApplicationContext("Beans.xml");StudentJDBCTemplatestudentJDBCTemplate=(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--------");Liststudents=studentJDBCTemplate.listStudents();for(Studentrecord: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 -----");Studentstudent=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"?>
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
創建源代碼和bean配置文件完成后,讓我們運行應用程序。如果一切順利,這將打印以下信息:
------Records Creation--------
Created Record Name = Zara Age = 11
Created Record Name = Nuha Age = 2
Created Record Name = Ayan Age = 15
------Listing Multiple Records--------
ID : 1, Name : Zara, Age : 11
ID : 2, Name : Nuha, Age : 2
ID : 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框架手冊。
¥ 我要打賞
糾錯/補充
收藏
加QQ群啦,易百教程官方技術學習群
注意:建議每個人選自己的技術方向加群,同一個QQ最多限加 3 個群。
總結
以上是生活随笔為你收集整理的jdbc java例子_Spring JDBC 例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java获取服务器信息吗_java获取服
- 下一篇: leetcode103JAVA_[Lee