[Spring Boot] 스프링 데이터 - MySQL

dsunni·2020년 8월 8일
0

MYSQL 설정하기

의존성 추가

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

mysql 접속 connector 추가


MYSQL 연결

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=dsunni
spring.datasource.password=pass3

Warning들이 뜨면 ?useSSL=false&allowPublicKeyRetrieval=true을 url 끝에 붙여주면 된다.


DB, 사용자 생성 후 접속

mysql -u root -p로 mysql에 접속한 후 springboot라는 이름의 Database, dsunni (pw: pass) User 생성

mysql -u root -p
create user 'dsunni' identified by 'pass';
grant all privileges on *.* to 'dsunni'@'%';
create database springboot;

mysql -u dsunni -p

MySQLRunner.java

@Component
public class MySQLRunner implements ApplicationRunner {
    @Autowired
    DataSource dataSource;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try(Connection connection = dataSource.getConnection()) {
            System.out.println(dataSource.getClass());
            System.out.println(connection.getMetaData().getURL());
            System.out.println(connection.getMetaData().getUserName());

            Statement statement = connection.createStatement();
            String sql = "CREATE TABLE USER(ID INTEGER NOT NULL, name VARCHAR(255), PRIMARY KEY (id))";
            statement.executeUpdate(sql);
        }
        jdbcTemplate.execute("INSERT INTO USER VALUES (1, 'keesun')");
        jdbcTemplate.execute("INSERT INTO USER VALUES (2, 'dsunni')");
    }
}

mysql> show tables;
+----------------------+
| Tables_in_springboot |
+----------------------+
| user                 |
+----------------------+
1 row in set (0.00 sec)

mysql> select * from user;
+----+--------+
| ID | name   |
+----+--------+
|  1 | keesun |
|  2 | dsunni |
+----+--------+

DB에 값이 잘 들어온 것을 확인할 수 있다.

profile
https://dsunni.tistory.com/ 이사갑니답

0개의 댓글