springboot using JDBC to connect to MySQL database
Spring connects MySQL in many ways, such as jdbc,spring Jpa,hibeirnate,mybatis, this article mainly introduces using the simplest, lowest level JDBC way to connect MySQL database, JDBC Connection database, mainly inject JdbcTemplate, use JdbcTemplate to manipulate the database .
Create a user table in the test library in MySQL and insert two data to prepare for follow-up
second, add dependencies in Pom.xml
<!--Jdbc--><dependency><groupid>mysql</groupid><artifactid>mysql-connector-java </artifactid></dependency><dependency><groupid>org.springframework.boot</groupid ><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
iii. Adding profile configuration databases and other parameters
Under the Resource folder, add the Application.properties configuration file and enter the database parameters as follows:
############################################################## mysql############################################ ################ #spring. datasource.url=jdbc:mysql://127.0.0.1:3306/testspring.datasource.username= Rootspring.datasource.password=rootspring.datasource.driver-class-name= com.mysql.jdbc.driverspring.datasource.max-idle=10spring.datasource.max-wait=10000spring.datasource.min-idle= 5spring.datasource.initial-size=5
Iv. New entity class User.java, attributes corresponding to database user table
/** * @author Oyc * @Description: User entity class * @date 2018/7/8 22:51 */public class User { //subscriber ID private String ID; User name private String name; The age of the family private String ages; User sex private String sex; Getter, setter method} is omitted here
v. New test class Connection database
/** * @author Oyc * @Description: User Control class * @date 2018/7/8 22:10 */@Controller @requestmapping ("/JDBC") public class Jdbccontr Oller {@Resource private jdbctemplate jdbctemplate; @RequestMapping ("/userlist") public String getuserlist (Modelmap map) {String sql = ' SELECT * from user '; List<user> userlist = jdbctemplate.query (sql, new rowmapper<user> () {User user = null; @Override public User Maprow (ResultSet rs, int rowNum) throws SQLException {user = new user () ; User.setid (rs.getstring ("id")); User.setname (rs.getstring ("name")); User.setsex (rs.getstring ("Sex")); User.setage (rs.getstring ("Age")); return user; }}); for (User user:userlist) {System.out.println (User.getname ()); } map.addattribute ("Users", userlist); return "user"; }}
Vi. a new Thymeleaf template page user.html for displaying the list of user information
Vii. use of browser testing
Spring Boot Starter Series seven (springboot using JDBC to connect to MySQL database)