LoginSignup
2
3

More than 1 year has passed since last update.

Spring bootでmysqlに接続する

Posted at

環境

・Windows10
・MySQL5.7

手順

1.依存関係の定義

SpringJDBCを使ってmysqlに接続するために必要な依存関係を定義する。

https://qiita.com/niwasawa/items/024a01c502962eb90b1d
ここではMavenプロジェクトの場合の説明が載っている。

Gradleプロジェクトの場合も同様。以下を参考。
https://learning-collection.com/springboot%E5%85%A5%E9%96%80-vol-6%EF%BC%9A%E3%83%87%E3%83%BC%E3%82%BF%E3%83%99%E3%83%BC%E3%82%B9%E3%81%AE%E6%BA%96%E5%82%99%E3%82%92%E3%81%97%E3%82%88%E3%81%86/

build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    runtimeOnly 'mysql:mysql-connector-java'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
}

app.properties
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=java
spring.datasource.password=cafebabe
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:schema.sql
spring.sql.init.data-locations=classpath:data.sql
spring.sql.init.encoding=utf-8

以下項目は環境によって設定が異なる可能性が高いので注意が必要。

spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=pass
spring.sql.init.schema-locations=classpath:schema.sql
spring.sql.init.data-locations=classpath:data.sql

また、以下2つ

spring.sql.init.schema-locations=classpath:schema.sql
spring.sql.init.data-locations=classpath:data.sql

に関しては、src/main/resources配下のパスを記載する。
私の場合、resources直下にsqlを配置しているので、上記のようになる。

2.mysqlをインストール

私の場合以前すでにインストール済みだったため割愛。
以下ページが参考になりそう。
https://qiita.com/ryo-sato/items/bd026f5e627a746f1734

3.mysqlのサービス起動

・タスクマネージャでMySQLのサービス名を確認する

・コマンドプロンプトを管理者権限で実行する
https://qiita.com/takuya0301/items/df6cde3bbaf9e13ef8f0

・コマンドプロンプトで以下コマンドを実行

> net start <MySQLのサービス名>

私の環境の場合、

> net start MySQL57

となる。

3.データベースの作成

・MySqlにログインする
コマンドプロンプトで以下コマンドを実行

> mysql -u <ユーザ名> -p

・パスワードを求められるので、パスワードを入力する
(参考)Mysqlパスワードのリセット

・新しいデータベースを作成する

mysql> create database <DB名>;

DB名:testdbの場合の例は以下。

mysql> create database testdb;

・データベースが作成されたことを確認する

mysql> show databases;

4.アプリを起動する

参考サイト

MySQLのコマンド
spring公式サイト

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3