How does spring boot connect localhost MySQL

MySQLMySQLi Database

For this, use −


To understand the above syntax, let us create a table −

mysql> create table demo71
−> (
−> id int,
−> name varchar(20)
−> );
Query OK, 0 rows affected (3.81 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo71 values(100,'John');
Query OK, 1 row affected (0.13 sec)

mysql> insert into demo71 values(101,'David');
Query OK, 1 row affected (0.49 sec)

mysql> insert into demo71 values(102,'Bob');
Query OK, 1 row affected (0.15 sec)

Display records from the table using select statement −

mysql> select *from demo71;

This will produce the following output −

| id   | name  |
| 100  | John  |
| 101  | David |
| 102  | Bob  |
3 rows in set (0.00 sec)

To verify the above is working with local MySQL or not, you can write spring boot application to test.

Following is the file.

Following is the controller class code. The code is as follows −

package com.demo.controller;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
public class TableController {
   EntityManager entityManager;
   public String getData() {
      Query sqlQuery= entityManager.createNativeQuery("select name from demo71");
      List<String> result= sqlQuery.getResultList();
      StringBuilder sb=new StringBuilder();
      Iterator itr= result.iterator();
      while(itr.hasNext()) {
         sb.append(" ");
      return sb.toString();

Following is the main class. The Java code is as follows −

package com.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
public class JavaMysqlDemoApplication {
   public static void main(String[] args) {, args);

To run the above, go to the main class and right click and select “Run as Java Application”.After successfully executing, you need to hit below url.

The url is as follows −


This will produce the following output −

Published on 20-Nov-2020 12:03:07