<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
mysql 접속 connector 추가
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 끝에 붙여주면 된다.
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
@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에 값이 잘 들어온 것을 확인할 수 있다.