English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

SpringBoot JDBC example

Spring Boot provides bootstraps and libraries for connecting to our application via JDBC. Here, we are creating an application that connects to a Mysql database. It includes the following steps to create and configure JDBC using Spring Boot.

Create database

create database springbootdb

Create a table in mysql

create table user(id int UNSIGNED primary key not null auto_increment, name varchar(100), email varchar(100));

Create Spring Boot Project

Provide the project name and other information related to the project.

Provide dependencies

After completion, create the following files in the project.

Configure the database in the application.properties file.

//application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb
spring.datasource.username=root
spring.datasource.password=mysql
spring.jpa.hibernate.ddl-auto=create-drop

//SpringBootJdbcApplication.java

package com.w3codebox;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootJdbcApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootJdbcApplication.class, args);
    }
}

Create a controller to handle HTTP requests.

//SpringBootJdbcController.java

package com.w3codebox;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SpringBootJdbcController {
    @Autowired
    JdbcTemplate jdbc;  
    @RequestMapping("/insert")
    public String index(){
        jdbc.execute("insert into user(name,email)values('w3codebox','[email protected]')");
        return"data inserted Successfully";
    }
}

Run the application

Run SpringBootJdbcApplication.java The file is a Java application.

Now, open the browser and follow the following URL.

It indicates that the data has been successfully inserted. Let's confirm it by checking the mysql table.

Well, our application is running finely. Now, we can also perform other database operations.