20200910のMySQLに関する記事は9件です。

SQL(MySQL)入門! CREATE 編 (データベース)

MySQLのインストールが終わり、rootユーザーでログインが完了している前提で始めていきます。


環境
 Windows 10
 MySQL : version(5.7.28)
使用アプリ
 コマンドプロンプト(Windowsマーク押して「cmd」って打ったら出てくるやつ)


データベースの作成

データベース作成のクエリ文
CREATE DATABASE データベースの名前;
コメント 2020-09-10 195912.jpg
「sample_db」という名前のデータベースを作成しました。

Query OK. 1 row affected (0.00 sec)

このように表示されれば、データベースの作成に成功しています。

補足

データベースの文字化けに悩まされた場合は、文字コードを指定してデータベースを作成するクエリもあります。

CREATE DATABASE データベース名 DEFAULT CHARACTER SET 文字コード;

CREATE DATABASE character_db DEFAULT CHARACTER SET utf8;

コメント 2020-09-10 201013.jpg
汎用的な文字コードである「UTF-8」を指定してデータベースを作成することに成功しました。

データベースの表示 ・ 指定 ・ 確認 ・ 削除

表示

データベースの一覧を表示
SHOW DATABASES;
※SHOWコマンドはMySQL独自のもの(方言と呼ばれているもの)です

SHOW DATABASES;

コメント 2020-09-10 202110.jpg
先ほど作成した「sample_db」と「character_db」が表示されているのがわかるかと思います。その他にもデータベースがいくつかありますが、管理や運用などで必要なものをMySQLが自前で作成したデータベースなので、得に気にしなくて大丈夫です。(黒で塗りつぶされているところは僕が作成しているデータベースです。)

指定

データベースの指定
USE データベース名;

USE sample_db;

使いたいデータベースを指定します。
コメント 2020-09-10 202940.jpg
このような表示が出ればデータベースの指定は成功です。

確認

データベースの確認
SELECT DATABASE();

SELECT DATABASE();

今、使っているデータベースの確認ができます。
コメント 2020-09-10 203249.jpg
このように表示されればオッケーです。

補足

使っているデータベースのバージョンの確認

SELECT VERSION();

実行結果
スクリーンショット 2020-09-12 103831.jpg
このコマンドで現在のデータベースのバージョンを確認することができます。

削除

データベースの削除
DROP DATABASE データベース名;

DROP DATABASE character_db;

「character_db」を削除します。
※この方法で削除してしまったデータベースは基本的に復元することができないので、最新の注意を払って慎重に作業してください。
コメント 2020-09-10 230646.jpg
このように表示されればデータベースの削除は成功です。

本当に削除されたのか確認してみます。

SHOW DATABASES;

コメント 2020-09-10 231818.jpg

表示されたデータベース一覧から「character_db」が消えているのがわかります。

終わりに

SQL(MySQL)の第一歩!ということで、データベース作成、表示、指定、確認、削除と学んできました。
このあとはいよいよテーブル作成などに入っていきます。
SQLの基礎をしっかりと見につけていきたいと思います。

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

MySQLの学習に役立つリンク集

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

WSL2上のDockerでMySQLを構築する際のpermissionsの対策

前書き

WSL2 MySQLで検索してもなかなかpermissionの解決方法が見つからずにハマった人の為に記載する。(どいつもこいつもWindowsのDockerとリンクしやがって・・・GPU使わんのかい!)

環境

  • Windows10 Insider Preview 2004(20206.1000)
  • 4.19.128-microsoft-standard
  • Ubuntu 20.04 LTS

現象

docker-compose up -dでコンテナ起動をさせると以下のような感じでMySQLのコンテナが起動できない。

root@pc-name: docker-compose logs mysql
mysql_1   | mysqld: Cannot change permissions of the file 'private_key.pem' (OS errno 1 - Operation not permitted)
mysql_1   | 2020-09-10T05:04:53.449233Z 0 [ERROR] [MY-010295] [Server] Could not set file permission for private_key.pem
mysql_1   | 2020-09-10T05:04:53.449629Z 0 [ERROR] [MY-010119] [Server] Aborting

こいつ(permission)の対応策について記載したい

対応

/etc/wsl.confにマウントオプションを追加する。

追加するマウントオプション
[automount]
options = "metadata"

WSL2初めの方は基本存在しないと思うので以下の手順で対応する。
WSL2のディストリビューションに/etc/wsl.confを作成。

# ルートでログイン
user@pc-name:sudo -i
# wslのディストリビューションにwslの設定ファイルを新規作成
root@pc-name: sudo touch /etc/wsl.conf
# 設定ファイルを編集する。
root@pc-name: vi /etc/wsl.conf

マウントオプションを変更する。 iでviコマンドをinsertモードにして以下を入力。

[automount]
options = "metadata"

ESCを押下後、上書き保存(:wq)し、WSLを再起動。

# ルートログアウト
root@pc-name:exti
# wsl ログアウト
user@pc-name:exit
# WSL シャットダウン
wsl --shutdown
# WSLを起動+ログイン
wsl

これで再度Docker関係でPermissionのエラーが消えていると思います。

おまけ

以下のようなログは/var/lib/mysqlのマウントディレクトリが既に存在する為
そのディレクトリを削除することで解決する。

root@pc-name: docker-compose logs mysql
...
mysql_1   | 2020-09-10T05:00:42.590708Z 0 [ERROR] [MY-010457] [Server] --initialize specified but the data directory has files in it. Aborting.
mysql_1   | 2020-09-10T05:00:42.590714Z 0 [ERROR] [MY-013236] [Server] The designated data directory /var/lib/mysql/ is unusable. You can remove all files that the server added to it.
mysql_1   | 2020-09-10T05:00:42.590777Z 0 [ERROR] [MY-010119] [Server] Aborting
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【NestJS】自己結合のSQLをTypeORMで書いた【MySQL】

前提

mysql: 5.7.19
@nestjs/common: 6.7.2
@nestjs/typeorm: 7.1.0
typeorm: 0.2.25
typescript: 3.6.3

やりたいこと

・自分にいいねしてきたユーザのユーザIDのリストを取得する
・自分がブロックしたユーザと、自分にいいね後にブロックしてきたユーザは取得しない
・自分にいいねがついた日時順と、
自分にいいねしてきたユーザの中で、いいね数が多いユーザの順で
ソートの切り分けができるようにする。

Entity

◆LikeEntity いいねテーブル

物理 論理
id like id
user_id いいねしたユーザのID
target_user_id いいねされたユーザのID
created_date いいねした日時

※user_idとtarget_user_idはUNIQUEインデックス

◆BlockEntity ブロックテーブル

物理 論理
id block id
user_id ブロックしたユーザのID
target_user_id ブロックされたユーザのID
created_date ブロックした日時

※user_idとtarget_user_idはUNIQUEインデックス

SQL

自分にいいねがついた日時順

方針

単純にlikeテーブルからいいね対象が自分であるレコードを抽出して、
created_dateでORDER BY

-- ?は自分のユーザIDが入る
SELECT
    `likeT`.`user_id` AS `likeT_user_id` -- いいねしたユーザのユーザID
FROM
    `like` `likeT`
WHERE
    `likeT`.`target_user_id` = ? -- いいね対象が自分であるレコード
-- ブロック・被ブロックは除外
AND NOT EXISTS(
        SELECT
            id
        FROM
            `block` `blockT`
        WHERE
            (
                `blockT`.`target_user_id` = `likeT`.`user_id`
            AND `blockT`.`user_id` = ?
            )
        OR  (
                `blockT`.`user_id` = `likeT`.`user_id`
            AND `blockT`.`target_user_id` = ?
            )
    )
ORDER BY
    `likeT`.`created_date` DESC

いいねが多い人順

方針

登録されているレコードを下記とする場合

id user_id target_user_id
1 a me
2 b me
3 c me
4 d me
5 1a a
6 1b a
7 1c b
8 1d b
9 1e b
10 1f c

①自分にいいねしてるユーザはaさん、bさん、cさん、dさん

id user_id target_user_id
1 a me
2 b me
3 c me
4 d me

②aさん、bさん、cさん、dさんがいいね対象になっているレコード(dさん無し)

id user_id target_user_id
5 1a a
6 1b a
7 1c b
8 1d b
9 1e b
10 1f c

②aさん、bさん、cさん、dさんがいいね対象になっているレコードを集約してカウントする

target_user_id liked_cnt 補足
a 2 ← aさんがもらってるいいね数
b 3 ← bさんがもらってるいいね数
c 1 ← cさんがもらってるいいね数
d 0 ← dさんがもらってるいいね数

①自分がいいね対象のレコードに、
②自分にいいねしたユーザの被いいね数のカラムを結合する
(key: ①.user_id = ②.target_user_id)

user_id target_user_id liked_cnt
a me 2
b me 3
c me 1
d me 0

liked_cntでORDER BY

-- ?は自分のユーザIDが入る
SELECT
    `likeT`.`user_id` AS `likeT_user_id` -- いいねしたユーザのユーザID
FROM
    `like` `likeT` -- ①
    -- ソート対象であるいいね数をカウントした集合②を作成し、自己結合する
    LEFT JOIN
        (
            -- いいねされたユーザID毎に、いいねされた件数をカウントする
            SELECT
                `likeT2`.`target_user_id` AS `targetUserId`,
                COUNT(`likeT2`.`target_user_id`) AS `likedCnt`
            FROM
                `like` `likeT2`
            GROUP BY
                `likeT2`.`target_user_id`
        ) `likedCntT`
    ON  `likeT`.`user_id` = likedCntT.targetUserId
WHERE
    `likeT`.`target_user_id` = ? -- いいね対象が自分であるレコード
-- ブロック・被ブロックは除外
AND NOT EXISTS(
        SELECT
            id
        FROM
            `block` `blockT`
        WHERE
            (
                `blockT`.`target_user_id` = `likeT`.`user_id`
            AND `blockT`.`user_id` = ?
            )
        OR  (
                `blockT`.`user_id` = `likeT`.`user_id`
            AND `blockT`.`target_user_id` = ?
            )
    )
ORDER BY
    IFNULL(`likedCntT`.`likedCnt`, 0) DESC,
    `likeT`.`created_date` DESC -- 第二ソート

TypeORM

import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { Like } from "src/entities/Like";

enum SortType {
    Good, // いいね数
    RecievedDate // いいね受け取った日時
}

constructor(
    @InjectRepository(Like)
    private readonly likeRepository: Repository<Like>,
) {}

async searchMyLikers(
    myUserId: string,
    sortType: SortType = null
): Promise<Like[]> {
    const queryBuilder = this.likeRepository
        .createQueryBuilder("likeT")
        .select("likeT.userId");

    // いいね順の場合のみ自己結合
    if (sortType === LikerSortType.Good) {
        queryBuilder.leftJoin(
            subQuery => {
                return subQuery
                    .select("likeT2.targetUserId", "targetUserId")
                    .addSelect("COUNT(likeT2.targetUserId)", "likedCnt")
                    .from(Like, "likeT2")
                    .groupBy("likeT2.targetUserId");
            },
            "likedCntT",
            "likeT.userId = likedCntT.targetUserId"
        );
    }

    queryBuilder
        .where("likeT.targetUserId = :myUserId", { myUserId })
        .andWhere(
            qb =>
                "NOT EXISTS " +
                qb
                    .subQuery()
                    .select("id")
                    .from(Block, "blockT")
                    .where(
                        new Brackets(qb => {
                            qb.where(
                                "blockT.targetUserId = likeT.userId"
                            ).andWhere("blockT.userId = :myUserId", {
                                myUserId
                            });
                        })
                    )
                    .orWhere(
                        new Brackets(qb => {
                            qb.where(
                                "blockT.userId = likeT.userId"
                            ).andWhere("blockT.targetUserId = :myUserId", {
                                myUserId
                            });
                        })
                    )
                    .getQuery()
        );

    if (sortType === LikerSortType.RecievedDate) {
        queryBuilder.orderBy("likeT.createdDate", "DESC");
    } else if (sortType === LikerSortType.Good) {
        queryBuilder
            .orderBy("IFNULL(`likedCntT`.`likedCnt`, 0)", "DESC")
            .addOrderBy("likeT.createdDate", "DESC");
    }

    console.log("sql:", queryBuilder.getSql());

    return await queryBuilder.getMany();
}
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【TypeORM】件数ソートの為の自己結合のSQLをTypeORMで書いた【MySQL】

前提

mysql: 5.7.19
@nestjs/common: 6.7.2
@nestjs/typeorm: 7.1.0
typeorm: 0.2.25
typescript: 3.6.3

やりたいこと

・自分にいいねしてきたユーザのユーザIDのリストを取得する
・自分がブロックしたユーザと、自分にいいね後にブロックしてきたユーザは取得しない
・自分にいいねがついた日時順と、
自分にいいねしてきたユーザの中で、いいね数が多いユーザの順で
ソートの切り分けができるようにする。

Entity

◆LikeEntity

物理 論理
id like id
user_id いいねしたユーザのID
target_user_id いいねされたユーザのID
created_date いいねした日時

※user_idとtarget_user_idはUNIQUEインデックス

◆BlockEntity

物理 論理
id block id
user_id ブロックしたユーザのID
target_user_id ブロックされたユーザのID
created_date ブロックした日時

※user_idとtarget_user_idはUNIQUEインデックス

SQL

自分にいいねがついた日時順

方針

単純にlikeテーブルからいいね対象が自分であるレコードを抽出して、
created_dateでORDER BY

-- ?は自分のユーザIDが入る
SELECT
    `likeT`.`user_id` AS `likeT_user_id` -- いいねしたユーザのユーザID
FROM
    `like` `likeT`
WHERE
    `likeT`.`target_user_id` = ? -- いいね対象が自分であるレコード
-- ブロック・被ブロックは除外
AND NOT EXISTS(
        SELECT
            id
        FROM
            `block` `blockT`
        WHERE
            (
                `blockT`.`target_user_id` = `likeT`.`user_id`
            AND `blockT`.`user_id` = ?
            )
        OR  (
                `blockT`.`user_id` = `likeT`.`user_id`
            AND `blockT`.`target_user_id` = ?
            )
    )
ORDER BY
    `likeT`.`created_date` DESC

いいねが多い人順

方針

登録されているレコードを下記とする場合

id user_id target_user_id
1 a me
2 b me
3 c me
4 1a a
5 1b a
6 1c b
7 1d b
8 1e b
9 1f c

①自分にいいねしてるユーザはaさん、bさん、cさん

id user_id target_user_id
1 a me
2 b me
3 c me

②aさん、bさん、cさんがいいね対象になっているレコード

id user_id target_user_id
4 1a a
5 1b a
6 1c b
7 1d b
8 1e b
9 1f c

②aさん、bさん、cさんがいいね対象になっているレコードを集約してカウントする

target_user_id liked_cnt 補足
a 2 ← aさんがもらってるいいね数
b 3 ← bさんがもらってるいいね数
c 1 ← cさんがもらってるいいね数

①自分がいいね対象のレコードに、
②自分にいいねしたユーザの被いいね数のカラムを結合する
(key: ①.user_id = ②.target_user_id)

user_id target_user_id liked_cnt
a me 2
b me 3
c me 1

liked_cntでORDER BY

-- ?は自分のユーザIDが入る
SELECT
    `likeT`.`user_id` AS `likeT_user_id` -- いいねしたユーザのユーザID
FROM
    `like` `likeT`
    -- ソート対象であるいいね数をカウントした集合を作成し、自己結合する
    LEFT JOIN
        (
            -- いいねされたユーザID毎に、いいねされた件数をカウントする
            SELECT
                `likeT2`.`target_user_id` AS `targetUserId`,
                COUNT(`likeT2`.`target_user_id`) AS `likedCnt`
            FROM
                `like` `likeT2`
            GROUP BY
                `likeT2`.`target_user_id`
        ) `likedCntT`
    ON  `likeT`.`user_id` = likedCntT.targetUserId
WHERE
    `likeT`.`target_user_id` = ? -- いいね対象が自分であるレコード
-- ブロック・被ブロックは除外
AND NOT EXISTS(
        SELECT
            id
        FROM
            `block` `blockT`
        WHERE
            (
                `blockT`.`target_user_id` = `likeT`.`user_id`
            AND `blockT`.`user_id` = ?
            )
        OR  (
                `blockT`.`user_id` = `likeT`.`user_id`
            AND `blockT`.`target_user_id` = ?
            )
    )
ORDER BY
    IFNULL(`likedCntT`.`likedCnt`, 0) DESC,
    `likeT`.`created_date` DESC -- 第二ソート

TypeORM

import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { Like } from "src/entities/Like";

enum SortType {
    Good, // いいね数
    RecievedDate // いいね受け取った日時
}

constructor(
    @InjectRepository(Like)
    private readonly likeRepository: Repository<Like>,
) {}

async searchMyLikers(
    myUserId: string,
    sortType: SortType = null
): Promise<Like[]> {
    const queryBuilder = this.likeRepository
        .createQueryBuilder("likeT")
        .select("likeT.userId");

    if (sortType === LikerSortType.Good) {
        queryBuilder.leftJoin(
            subQuery => {
                return subQuery
                    .select("likeT2.targetUserId", "targetUserId")
                    .addSelect("COUNT(likeT2.targetUserId)", "likedCnt")
                    .from(Like, "likeT2")
                    .groupBy("likeT2.targetUserId");
            },
            "likedCntT",
            "likeT.userId = likedCntT.targetUserId"
        );
    }

    queryBuilder
        .where("likeT.targetUserId = :myUserId", { myUserId })
        .andWhere(
            qb =>
                "NOT EXISTS " +
                qb
                    .subQuery()
                    .select("id")
                    .from(Block, "blockT")
                    .where(
                        new Brackets(qb => {
                            qb.where(
                                "blockT.targetUserId = likeT.userId"
                            ).andWhere("blockT.userId = :myUserId", {
                                myUserId
                            });
                        })
                    )
                    .orWhere(
                        new Brackets(qb => {
                            qb.where(
                                "blockT.userId = likeT.userId"
                            ).andWhere("blockT.targetUserId = :myUserId", {
                                myUserId
                            });
                        })
                    )
                    .getQuery()
        );

    if (sortType === LikerSortType.RecievedDate) {
        queryBuilder.orderBy("likeT.createdDate", "DESC");
    } else if (sortType === LikerSortType.Good) {
        queryBuilder
            .orderBy("IFNULL(`likedCntT`.`likedCnt`, 0)", "DESC")
            .addOrderBy("likeT.createdDate", "DESC");
    }

    console.log("sql:", queryBuilder.getSql());

    return await queryBuilder.getMany();
}
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Mysqlにデータベースを変更する

database.ymlの中身を以下のように書き換えてください。

config/database.yml
default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password:
  socket: /tmp/mysql.sock
development:
  <<: *default
  database: amazon_app_mysql_development
test:
  <<: *default
  database: amazon_app_mysql_test
production:
  <<: *default
  database: amazon_app_mysql_production
  username: amazon_app_mysql
  password: <%= ENV['AMAZON_APP_MYSQL_DATABASE_PASSWORD'] %>

sqliteをコメントアウトする

Gemfile
#gem 'sqlite3', '~> 1.4'

mysqlを追加する

Gemfile
gem 'mysql2', '>= 0.4.4'

mysql2を更新させ、反映させる

ターミナル
$ bundle update

DBを初期化

$ rails db:migrate:reset
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

JavaでDBlayerの実装(RDB、MySQL)

MySQL

DBConstants

まず、DB接続用の定数を定義しよう!!

DBConstants
public class Constants {

    public static final String DB_SERVER = "localhost";
    public static final String DB_PORT = "0000";
    public static final String DB_DRIVER = "com.mysql.jdbc.Driver";
    public static final String DB_USERNAME = "root";
    public static final String DB_PASSWORD = "root";
    public static final String DB_URL = "jdbc:mysql://localhost:0000/schema?autoReconnect=true&useSSL=false";
}

DBConection

つぎに、データベースに接続するためのクラスをつくろう!!

DBConection
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConn {

    //MySQLに接続
    public Connection conn;
    //ステートメントを作成
    public Statement stmt;

    public DBConn() {
        try {
            Class.forName(Constants.DB_DRIVER);

            conn = DriverManager.getConnection(Constants.DB_URL, Constants.DB_USERNAME, Constants.DB_PASSWORD);
            stmt = conn.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void finalize() {
        try {
            conn.close();
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

DBEntity

お次は、Entityクラスをつくろう!!

DBEntity
public class UserEntity {

    private int id = 1;

    private String username = null;

    private String password = null;

    private Date lastlogin = null;

    private boolean deleteflg = false;

    private String name = null;

    public UserEntity() {
        this(0, null, null);
    }

    public UserEntity(int id, String username, String password) {
        this.setId(id);
        this.setUsername(username);
        this.setPassword(password);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getLastlogin() {
        return lastlogin;
    }

    public void setLastlogin(Date lastlogin) {
        this.lastlogin = lastlogin;
    }

    public boolean getDeleteflg() {
        return deleteflg;
    }

    public void setDeleteflg(boolean deleteflg) {
        this.deleteflg = deleteflg;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

DBDAO

最後に、DAOクラスをつくろう!!
(先につくったDBConnectionクラスを継承させよう)

DBDAO
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserDAO extends DBConn {

    public List<UserEntity> read(String wherestatement, String orderby, String ascdsc) throws SQLException {

        List<UserEntity> listuserEntity = new ArrayList<>();
        String sqlQuery = "SELECT * FROM user";

        if(wherestatement != "") {
            sqlQuery += " WHERE " + wherestatement;
        }

        if(orderby != "") {
            sqlQuery += " ORDER BY " + orderby;
        }

        if(ascdsc != "") {
            sqlQuery += " " + ascdsc;
        }

            //SELECT
            ResultSet rset = stmt.executeQuery(sqlQuery);
            while(rset.next()) {
                UserEntity userEntity = new UserEntity();
                userEntity.setId(rset.getInt("id"));
                userEntity.setUsername(rset.getString("username"));
                userEntity.setPassword(rset.getString("password"));
                userEntity.setLastlogin(rset.getDate("lastlogin"));
                userEntity.setDeleteflg(rset.getBoolean("deleteflg"));
                userEntity.setName(rset.getString("name"));
                listuserEntity.add(userEntity);
            }

            //結果セットをクローズ
            rset.close();

        return listuserEntity;
    }

    public UserEntity readId(int id) throws SQLException {

        UserEntity userEntity = new UserEntity();

        //SELECT
        ResultSet rset = stmt.executeQuery("SELECT * FROM user WHERE id = "+ id);
        while(rset.next()) {
            userEntity.setId(rset.getInt("id"));
            userEntity.setUsername(rset.getString("username"));
            userEntity.setPassword(rset.getString("password"));
            userEntity.setLastlogin(rset.getDate("lastlogin"));
            userEntity.setDeleteflg(rset.getBoolean("deleteflg"));
            userEntity.setName(rset.getString("name"));
        }

        //結果セットをクローズ
        rset.close();

        return userEntity;
    }

    public void add(UserEntity userEntity) throws SQLException {

        int id = userEntity.getId();
        String username = userEntity.getUsername();
        String password = userEntity.getPassword();
        Date lastlogin = userEntity.getLastlogin();
        boolean deleteflg = userEntity.getDeleteflg();
        String name = userEntity.getName();

        //INSERT
        int insert = stmt.executeUpdate("INSERT INTO user VALUES ("+ id +",'" +username +"','" + password +"'," + lastlogin + "," + deleteflg + ",'" + name  + ")");
    }

    public void update(int id, UserEntity userEntity) throws SQLException {

        int userid = userEntity.getId();
        String username = userEntity.getUsername();
        String password = userEntity.getPassword();
        Date lastlogin = userEntity.getLastlogin();
        boolean deleteflg = userEntity.getDeleteflg();
        String name = userEntity.getName();

        //UPDATE
        int rset = stmt.executeUpdate("UPDATE user SET id =" + userid +"," + "username = '" +username +"'," + "password = '" + password +"',"
                + "lastlogin =" + lastlogin + "," + "deleteflg =" + deleteflg + "," + "name = '" + name + " WHERE id =" + id);
    }

    public void delete(int id) throws SQLException {

        //DELETE
        int rset = stmt.executeUpdate("DELETE FROM user WHERE id = "+ id);
    }

    public List<UserEntity> readwhere(String wherestatement, String orderby, String ascdsc) throws SQLException {

        List<UserEntity> listuserEntity = new ArrayList<>();

        //SELECT
        ResultSet rset = stmt.executeQuery("SELECT * FROM user WHERE " + wherestatement + " ORDER BY " + orderby +" " + ascdsc);
        while(rset.next()) {
            UserEntity userEntity = new UserEntity();
            userEntity.setId(rset.getInt("id"));
            userEntity.setUsername(rset.getString("username"));
            userEntity.setPassword(rset.getString("password"));
            userEntity.setLastlogin(rset.getDate("lastlogin"));
            userEntity.setDeleteflg(rset.getBoolean("deleteflg"));
            userEntity.setName(rset.getString("name"));
            listuserEntity.add(userEntity);
        }

        rset.close();

       return listuserEntity;
    }

}
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Moodleインストール

Moodleのインストール情報を参考に、Moodleをインストールする。

必要なパッケージのインストール

最初からこのパッケージが必要、と分かっているわけではない。ブラウザでのインストール手順中、必要なPHPのパッケージチェックの結果として分かるものもある。

$ sudo apt install -y apache2 php libapache2-mod-php php-curl php-zip php-mysqli php-xml php-gd php-intl php-mbstring php-soap php-xmlrpc

$ sudo apt install -y graphviz aspell ghostscript clamav php-pspell php-mysql php-ldap 

ソースコードの取得

$ cd /opt
$ sudo git clone git://git.moodle.org/moodle.git
Cloning into 'moodle'...
remote: Counting objects: 1174897, done.
remote: Compressing objects: 100% (3234/3234), done.
remote: Total 1174897 (delta 5459), reused 6984 (delta 5021)
Receiving objects: 100% (1174897/1174897), 399.60 MiB | 385.00 KiB/s, done.
Resolving deltas: 100% (874153/874153), done.
Checking out files: 100% (21227/21227), done.
$ cd moodle
$ sudo git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/MOODLE_13_STABLE
  remotes/origin/MOODLE_14_STABLE
  remotes/origin/MOODLE_15_STABLE
  remotes/origin/MOODLE_16_STABLE
  remotes/origin/MOODLE_17_STABLE
  remotes/origin/MOODLE_18_STABLE
  remotes/origin/MOODLE_19_STABLE
  remotes/origin/MOODLE_20_STABLE
  remotes/origin/MOODLE_21_STABLE
  remotes/origin/MOODLE_22_STABLE
  remotes/origin/MOODLE_23_STABLE
  remotes/origin/MOODLE_24_STABLE
  remotes/origin/MOODLE_25_STABLE
  remotes/origin/MOODLE_26_STABLE
  remotes/origin/MOODLE_27_STABLE
  remotes/origin/MOODLE_28_STABLE
  remotes/origin/MOODLE_29_STABLE
  remotes/origin/MOODLE_30_STABLE
  remotes/origin/MOODLE_310_STABLE
  remotes/origin/MOODLE_31_STABLE
  remotes/origin/MOODLE_32_STABLE
  remotes/origin/MOODLE_33_STABLE
  remotes/origin/MOODLE_34_STABLE
  remotes/origin/MOODLE_35_STABLE
  remotes/origin/MOODLE_36_STABLE
  remotes/origin/MOODLE_37_STABLE
  remotes/origin/MOODLE_38_STABLE
  remotes/origin/MOODLE_39_STABLE
  remotes/origin/master

$ sudo git branch --track MOODLE_39_STABLE origin/MOODLE_39_STABLE
Branch 'MOODLE_39_STABLE' set up to track remote branch 'MOODLE_39_STABLE' from 'origin'.

$ sudo git checkout MOODLE_39_STABLE
Switched to branch 'MOODLE_39_STABLE'
Your branch is up to date with 'origin/MOODLE_39_STABLE'.

$ sudo cp -R /opt/moodle /var/www/html/
$ sudo chown -R www-data /var/www/moodledata
$ sudo chmod -R 0755 /var/www/html/moodle

/var/www/moodledataは、後ほどブラウザからのインストールの際に指定することになるので、覚えておく。

MySQLの設定

mysql.cnfに以下の3行を追記する。

/etc/mysql/mysql.conf.d/mysqld.cnf
default_storage_engine = innodb
innodb_file_per_table = 1
innodb_file_format = Barracuda

MySQLを再起動する。

$ sudo service mysql restart

MySQL上でデータベースの作成とユーザの作成を行う。

$ sudo mysql -u root -p

パスワードはなし。エンターキーで進める。

以下のSQLのうち、usernamepasswordは適切なものを設定する。

CREATE DATABASE moodle DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
create user 'username'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,CREATE TEMPORARY TABLES,DROP,INDEX,ALTER ON moodle.* TO 'username'@'localhost';
quit;

ここまで出来たら、次はブラウザ上での操作となる。

Moodle

ブラウザからMoodleにアクセス。

Step1 言語の選択

Moodle_01.png

Step2 パスの確認

Moodle_02.png

パスは、インストールした場所と合わせて確認する。

Step3 データベースドライバの選択

Moodle_03.png

データベースドライバはmysqliを選択する。

Step4 データベース設定

Moodle_04.png

MySQLの設定にて設定した値を適用する。

Step5 config.php

Moodle_05.png

この画面に表示されているPHPコードを、/var/www/html/moodle/config.phpというファイルに記述する。

Step6 著作権表示

Moodle_06.png

著作権表示。そのまま続ける。

Step7 PHPパッケージのチェック

以下の追加パッケージのうちチェックとなっているものは、sudo apt-get installでのインストールを行ったのち、 "Apache2の再起動をした上で" もう一度この画面でチェックする。httpsは、今回はそのまま。

Moodle_07.png

Moodle_08.png

Step8 Moodleモジュールのインストール

それなりの時間がかかるので、状況を確認しながら待つ。

Moodle_09.png

Moodle_10.png

Step9 最高管理者アカウントの作成

Moodle_11.png

Moodle_12.png

Step10 フロントページ設定など、基本設定

Moodle_13.png

Moodle_14.png

Moodle_15.png

noreply@localhostをそのままにしておいたら怒られた。適切なメールアドレスを設定する。

Step11 終了

ダッシュボードが表示されて、インストール完了。

Moodle_16.png

振り返り

  1. 全部コマンドラインでインストールできるなら楽なのだが、そういうものは無い様子。
  2. 依存PHPパッケージのチェックは事前にコマンドラインでやりたい・・・
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

dieselインストール(mysql版)

dieselを試す。目標はMoodleのデータベースの読み取り。

MySQL系パッケージのインストール

サーバ、クライアントは無くてもdiesel自体には関係ないはず。

$ sudo apt install -y mysql-server mysql-client libmysqlclient-dev

diesel、diesel_cliをプロジェクトに追加。

$ cargo add diesel diesel_cli
    Updating 'https://github.com/rust-lang/crates.io-index' index
      Adding diesel v1.4.5 to dependencies
      Adding diesel_cli v1.4.1 to dependencies

diesel、diesel_cliをインストールする。--no-default-featuresは、デフォルトのフィーチャをインストールされないように指定。--features mysqlで、MySQL用のフィーチャを有効にする。

$ cargo install diesel_cli --no-default-features --features mysql
    Updating crates.io index
  Installing diesel_cli v1.4.1
   Compiling libc v0.2.76
   Compiling proc-macro2 v1.0.20
   Compiling unicode-xid v0.2.1
   Compiling syn v1.0.40
   Compiling cfg-if v0.1.10
   Compiling autocfg v1.0.1
   Compiling getrandom v0.1.14
   Compiling matches v0.1.8
   Compiling memchr v2.3.3
   Compiling pkg-config v0.3.18
   Compiling tinyvec v0.3.4
   Compiling adler v0.2.3
   Compiling unicode-xid v0.0.4
   Compiling serde_derive v1.0.115
   Compiling byteorder v1.3.4
   Compiling gimli v0.22.0
   Compiling bitflags v1.2.1
   Compiling ppv-lite86 v0.2.9
   Compiling quote v0.3.15
   Compiling regex v0.2.11
   Compiling ucd-util v0.1.8
   Compiling lazy_static v1.4.0
   Compiling serde v1.0.115
   Compiling percent-encoding v1.0.1
   Compiling rustc-demangle v0.1.16
   Compiling object v0.20.0
   Compiling unicode-width v0.1.8
   Compiling utf8-ranges v1.0.4
   Compiling ansi_term v0.11.0
   Compiling remove_dir_all v0.5.3
   Compiling vec_map v0.8.2
   Compiling strsim v0.8.0
   Compiling unicode-bidi v0.3.4
   Compiling num-traits v0.2.12
   Compiling num-integer v0.1.43
   Compiling unicode-normalization v0.1.13
   Compiling miniz_oxide v0.4.1
   Compiling synom v0.11.3
   Compiling mysqlclient-sys v0.2.4
   Compiling addr2line v0.13.0
   Compiling regex-syntax v0.5.6
   Compiling thread_local v0.3.6
   Compiling textwrap v0.11.0
   Compiling idna v0.1.5
   Compiling syn v0.11.11
   Compiling backtrace v0.3.50
   Compiling atty v0.2.14
   Compiling time v0.1.44
   Compiling quote v1.0.7
   Compiling aho-corasick v0.6.10
   Compiling url v1.7.2
   Compiling rand_core v0.5.1
   Compiling error-chain v0.10.0
   Compiling clap v2.33.3
   Compiling rand_chacha v0.2.2
   Compiling derive-error-chain v0.10.1
   Compiling chrono v0.4.15
   Compiling rand v0.7.3
   Compiling diesel_derives v1.4.1
   Compiling tempfile v3.1.0
   Compiling dotenv v0.10.1
   Compiling toml v0.4.10
   Compiling diesel v1.4.5
   Compiling migrations_internals v1.4.1
   Compiling diesel_cli v1.4.1
    Finished release [optimized] target(s) in 7m 09s
  Installing /home/vagrant/.cargo/bin/diesel
   Installed package `diesel_cli v1.4.1` (executable `diesel`)

振り返り

  1. この後、Moodleの既存テーブルからスキーマを取得するところまで持っていく。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む