20200518のMySQLに関する記事は4件です。

Docker内でMySQLにPythonで接続する

DocekrもMySQLも初心者用のメモ

github url: https://github.com/kenjiSpecial/docker_mysql_python_beginner

docker-compose.yml

docker-compose.yml
version: "3"

services:
  mysql_db:
    container_name: "mysql_db"
    image: mysql:5.7
    command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
    volumes:
      - db_volume:/var/lib/mysql
    environment: # Set up mysql database name and password
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: employees
      MYSQL_USER: user
      MYSQL_PASSWORD: password
    networks:
      - app-tier

  python3:
    restart: always
    build: ./python
    container_name: "python3"
    working_dir: "/root/"
    tty: true
    depends_on:
      - mysql_db
    networks:
      - app-tier
    volumes:
      - ./python:/root
      - pycache_volume:/root/.cache

networks:
  app-tier:
    driver: bridge

volumes:
  db_volume:
  pycache_volume:

DockerfileにPythonのコンテナ情報を入力する

Dockerfile
FROM python:3.7


# ADD . /root
COPY . /opt
WORKDIR /opt

RUN pip install -r requirements.txt

main.py

main.py
import mysql.connector as mysql
user_name = "user"
password = "password"
host = "mysql_db"  # docker-composeで定義したMySQLのサービス名
database_name = "employees"


conn = mysql.connect(
    host="mysql_db",
    user="user",
    passwd="password",
    port=3306,
    database="employees"
)

conn.ping(reconnect=True)

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

MySQLを始めてパスワード設定まで for Mac

はじめに

いままでphpmyadminとmysqlのgemに頼り切っていた私は最近、phpmyadminの脆弱性に気づきました。どうせならコマンドから操作したいと思ったのでMySQLを導入しようと思ったのですが、パスワード設定が思ったより難航したので参考にどうぞ。

環境: mysql 8.0.19  MacOS

まずインストール

Macにパッケージをインストールしていくにあたって、バージョン管理をしてくれるhomebrewというものが主流のようなのでまずhomebrewをインストールします。
ターミナルを開き、入力していきます。(ターミナルはMacにデフォルトで入っているもので構いません)

% /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

(homebrew公式ページより)

mysqlをインストール

% brew install mysql

ビールの絵文字が出てくればインストール成功。
brew listと打ってmysqlという文字が確認できればOK

初期設定

インストールした時点でサーバーは立ち上がっているのでルートユーザーでログインします。

% mysql -uroot
/////省略/////
mysql>

このようにmysql>と出て、sqlのコマンドを受け付けてくれるようになりました。

パスワードの設定

このままではセキュリティー上、パスワードがなくてもmysqlにアクセスできてしまうので、一応パスワードを設定します。

mysql> set password for root@localhost='ここにパスワード';
Query OK, 0 rows affected (0.01 sec)

mysql>

パスワードがちゃんと使えるのか確認
一回mysqlを抜けて再度ログインします
EnterPasswordで先ほど設定したパスワードを求められるので入力してmysql>で入力待ちの状態になればパスワードは設定されています。

mysql> quit
Bye
% mysql -uroot -p
Enter Password:

*注意 先ほどはmysql -urootでログインしましたがパスワードを設定後にこのコマンドでアクセスしようとすると

% mysql -uroot 
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

このようにパスワードなしではログインできません!とエラーが出ます。パスワード設定後は-urootの後に-pをつけることで正常にアクセスが可能です。

ついでに

このように始めはうまくパスワード設定ができてもログインができないことがあります。私の場合サーバーが立っていないということがよくあったのでそういうときはこうやって↓コマンド打ってサーバーを立ち上げましょう!

% mysql.server start
Starting MySQL
.. SUCCESS! 

私情ですが。。

プログラミング学習のことで話せる初心者の学生さん!もしよければ
twitterアカウントまでお願いします

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

CentOSにmysqlコマンドをインストールする方法

  • 環境
    • CentOS Linux release 7.8.2003 (Core)
    • 接続先 : MySQL8.0.20

やりたいこと : mysqlコマンドだけインストールしたい

以前、RDSに接続したくてUbuntuにmysqlコマンドだけインストールしたことがある。

DockerでMySQLデータベースとアプリケーションのコンテナを作成した。
なので今回は、データベース用のコンテナに接続するためにmysqlコマンドだけほしい。

MySQLリポジトリをインストールする

  1. MySQLリポジトリをインストールする
$ sudo rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-1.noarch.rpm
[sudo] password for ponsuke:
Retrieving https://dev.mysql.com/get/mysql80-community-release-el7-1.noarch.rpm
warning: /var/tmp/rpm-tmp.P6p8HL: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
Preparing...                          ################################# [100%]
Updating / installing...
   1:mysql80-community-release-el7-1  ################################# [100%]

欲しいバージョンが有効になっていることを確認する

  1. ほしいバージョンが有効になっていることを確認する
  2. ほしいバージョンが無効になっていたらyum-config-managerコマンドで有効化する
# ほしいバージョンが有効になっていることを確認する
$ sudo yum repolist enabled | grep mysql
Repository google-chrome is listed more than once in the configuration
mysql-connectors-community/x86_64 MySQL Connectors Community                 153
mysql-tools-community/x86_64      MySQL Tools Community                      110
mysql80-community/x86_64          MySQL 8.0 Community Server                 177

インストールする

  1. mysqlコマンドはmysql-community-clientに含まれている
  2. mysql-community-clientをインストールする
# mysqlコマンドはmysql-community-clientに含まれている
$ sudo yum search mysql-community-client
Loaded plugins: fastestmirror, ovl
Repository google-chrome is listed more than once in the configuration
Loading mirror speeds from cached hostfile
 * base: d36uatko69830t.cloudfront.net
 * epel: d2lzkl7pfhq30w.cloudfront.net
 * extras: d36uatko69830t.cloudfront.net
 * updates: d36uatko69830t.cloudfront.net
============================================================================ N/S matched: mysql-community-client =============================================================================
mysql-community-client.i686 : MySQL database client applications and tools
mysql-community-client.x86_64 : MySQL database client applications and tools

  Name and summary matches only, use "search all" for everything.


# mysql-community-clientをインストールする
$ sudo yum install -y mysql-community-client.x86_64
Loaded plugins: fastestmirror, ovl
Repository google-chrome is listed more than once in the configuration
Loading mirror speeds from cached hostfile
 * base: d36uatko69830t.cloudfront.net
 * epel: d2lzkl7pfhq30w.cloudfront.net
 * extras: d36uatko69830t.cloudfront.net
 * updates: d36uatko69830t.cloudfront.net
Resolving Dependencies
--> Running transaction check
---> Package mysql-community-client.x86_64 0:8.0.20-1.el7 will be installed
--> Processing Dependency: mysql-community-libs(x86-64) >= 8.0.11 for package: mysql-community-client-8.0.20-1.el7.x86_64
--> Running transaction check
---> Package mysql-community-libs.x86_64 0:8.0.20-1.el7 will be installed
--> Processing Dependency: mysql-community-common(x86-64) >= 8.0.11 for package: mysql-community-libs-8.0.20-1.el7.x86_64
--> Running transaction check
---> Package mysql-community-common.x86_64 0:8.0.20-1.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

==============================================================================================================================================================================================
 Package                                              Arch                                 Version                                      Repository                                       Size
==============================================================================================================================================================================================
Installing:
 mysql-community-client                               x86_64                               8.0.20-1.el7                                 mysql80-community                                47 M
Installing for dependencies:
 mysql-community-common                               x86_64                               8.0.20-1.el7                                 mysql80-community                               609 k
 mysql-community-libs                                 x86_64                               8.0.20-1.el7                                 mysql80-community                               4.5 M

Transaction Summary
==============================================================================================================================================================================================
Install  1 Package (+2 Dependent packages)

Total download size: 52 M
Installed size: 256 M
Downloading packages:
warning: /var/cache/yum/x86_64/7/mysql80-community/packages/mysql-community-common-8.0.20-1.el7.x86_64.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
Public key for mysql-community-common-8.0.20-1.el7.x86_64.rpm is not installed
(1/3): mysql-community-common-8.0.20-1.el7.x86_64.rpm                                                                                                                  | 609 kB  00:00:00
(2/3): mysql-community-libs-8.0.20-1.el7.x86_64.rpm                                                                                                                    | 4.5 MB  00:00:00
(3/3): mysql-community-client-8.0.20-1.el7.x86_64.rpm                                                                                                                  |  47 MB  00:00:00
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                         138 MB/s |  52 MB  00:00:00
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
Importing GPG key 0x5072E1F5:
 Userid     : "MySQL Release Engineering <mysql-build@oss.oracle.com>"
 Fingerprint: a4a9 4068 76fc bd3c 4567 70c8 8c71 8d3b 5072 e1f5
 Package    : mysql80-community-release-el7-1.noarch (installed)
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
  Installing : mysql-community-common-8.0.20-1.el7.x86_64                                                                                                                                 1/3
  Installing : mysql-community-libs-8.0.20-1.el7.x86_64                                                                                                                                   2/3
  Installing : mysql-community-client-8.0.20-1.el7.x86_64                                                                                                                                 3/3
  Verifying  : mysql-community-client-8.0.20-1.el7.x86_64                                                                                                                                 1/3
  Verifying  : mysql-community-libs-8.0.20-1.el7.x86_64                                                                                                                                   2/3
  Verifying  : mysql-community-common-8.0.20-1.el7.x86_64                                                                                                                                 3/3

Installed:
  mysql-community-client.x86_64 0:8.0.20-1.el7

Dependency Installed:
  mysql-community-common.x86_64 0:8.0.20-1.el7                                                   mysql-community-libs.x86_64 0:8.0.20-1.el7

Complete!

アプリケーション用コンテナから接続してみる

$ mysql -h {MySQLのコンテナ名} -u root -D {データベース名} -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.20 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

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

【環境構築】MySQLのパスワードが分からず、最終的にディレクトリごと削除して解決した話。

はじめに

環境構築の際、MySQLのパスワードが分からず詰まったので、以下に解決まで至った流れを記していきます。
これはあくまで私の環境上の話なので、どこまで参考になるか分かりませんし、皆様のお時間を無駄にしたくはないので、最初に解決策と主に使用したコマンドを記載しておきます。

ご興味ある方は最後までご一読頂ければと思います。

解決策

  • mysqlの5.7系と8系がインストールされてたから8系を削除。
  • mysqlが5.7系のパスを指すようにzshrcで設定。
  • 過去にインストールしていたMySQL5.7系のパスワードが分からないから、sudo rm -rf /usr/local/var/mysqlでディレクトリごと削除。
  • 改めてbrew install mysql@5.7を実行し、完全に新しいrootユーザーが作成されたことで、パスワード無しでログインできた。

主に使用したコマンド

MySQL
- brew uninstall mysql
- which mysql
- ps aux | grep mysql
- source ~/.zshrc
- sudo rm -rf /usr/local/var/mysql

試したこと①とりあえずログインしようとしてみる

MySQLのバージョン確認。8系が入ってる。

$ mysql --version
> mysql  Ver 8.0.19 for osx10.15 on x86_64 (Homebrew)

パスワードが分からない。何も覚えてねえ、、

$ mysql.server start
Starting MySQL
.. SUCCESS! 

$ mysql -u root -p
> Enter password: 
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

$ mysql -u root   
> ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

勿論bundle exec rails db:createは実行できない。

$ bundle exec rails db:create
Access denied for user 'root'@'localhost' (using password: NO)
Couldn't create 'runteq_rails_advanced_development' database. Please check your configuration.
rails aborted!
Mysql2::Error::ConnectionError: Access denied for user 'root'@'localhost' (using password: NO)
$ which mysql
> /usr/local/bin/mysql

試したこと②MySQL8系をアンインストールし、5.7系を使ってみる

パスワードがわからんから一旦brew uninstall mysqlしてみると、8系がアンインストールされた。
which mysqlを打つとnot foundと出る。

$ brew uninstall mysql
Uninstalling /usr/local/Cellar/mysql/8.0.19... (286 files, 289.2MB)

$ which mysql
mysql not found
  • ps auxで現在実行されているプロセスを確認できる。
  • grepコマンドで文字列検索を行えるので、ps aux | grep mysqlを実行し、実行中のMySQLが無いか確認してみる。すると、mysqlの5.7系のプロセスが実行されている事が分かった。
    whichコマンドでは5.7系が見つからなかったけど、5.7系のプロセス自体は実行されているため、mysqlと打てば5.7系のディレクトリにパスが通るよう設定する。
$ ps aux | grep mysql
fune       617   0.0  0.0  4682956   2000   ??  S    30 420    1:29.79 /usr/local/opt/mysql@5.7/bin/mysqld --basedir=/usr/local/opt/mysql@5.7 --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/opt/mysql@5.7/lib/plugin --log-error=ryota21.local.err --pid-file=ryota21.local.pid
fune       497   0.0  0.0  4280012      8   ??  S    30 420    0:00.04 /bin/sh /usr/local/opt/mysql@5.7/bin/mysqld_safe --datadir=/usr/local/var/mysql
fune     30815   0.0  0.0  4268280    636 s000  R+    3:27PM   0:00.01 grep mysql

zshrcexport PATH="/usr/local/opt/mysql@5.7/bin:$PATH"と記載。

.zshrc
export PATH="/usr/local/opt/mysql@5.7/bin:$PATH

sourceコマンドでzshrcファイルに記載されているコマンドを実行し、パスを通す。

$ source ~/.zshrc`

which mysqlと打つと、zshrcで指定したパスを指すようになった。

$ which mysql
/usr/local/opt/mysql@5.7/bin/mysql

まだpasswordを空でEnter押してもログインできない。。。

$ mysql -u root -p
> Enter password: 
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

MySQL5.7系もアンインストールし、再インストールしてみる。
やっぱりパスワードが分からず、ログインできない、、?

$  mysql.server stop
Shutting down MySQL
.... SUCCESS!

mysqlの5.7系をアンインストール
$ brew uninstall mysql@5.7

mysqlの5.7系を再インストール
$ brew install mysql@5.7

mysqlを起動
$ mysql.server start

mysqlにログイン
$ mysql -uroot
> ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

$ mysql -u root -p
> Enter password: 
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

試したこと③:ディレクトリごとMySQLを削除

パスワードがマジで分からないので、もうディレクトリごと消してやれ、、!と決意。

一旦プロセスに残っているMySQLをmysql.server stopで停止させる。

$ ps aux | grep mysql     
fune     32217   0.0  0.0  4278520    676 s000  S+    3:41PM   0:00.01 grep mysql
fune     32210   0.0  0.4  4681888  31748 s000  S     3:38PM   0:00.41 /usr/local/Cellar/mysql@5.7/5.7.29/bin/mysqld --basedir=/usr/local/Cellar/mysql@5.7/5.7.29 --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/Cellar/mysql@5.7/5.7.29/lib/plugin --log-error=ryota21.local.err --pid-file=/usr/local/var/mysql/ryota21.local.pid
fune     32111   0.0  0.0  4280120    688 s000  S     3:38PM   0:00.04 /bin/sh /usr/local/Cellar/mysql@5.7/5.7.29/bin/mysqld_safe --datadir=/usr/local/var/mysql --pid-file=/usr/local/var/mysql/ryota21.local.pid

プロセスを停止する
$ mysql.server stop

grepしてみると、MySQLでgrepしたというプロセスしか残ってない。
MySQL自体のプロセスは止まっているということ。

$ ps aux | grep mysql
fune     32236   0.0  0.0  4278520    672 s000  S+    3:42PM   0:00.00 grep mysql

ディレクトリごとMySQLを削除する。

MySQLをアンインストールする
$ brew uninstall mysql@5.7

ディレクトリの中に削除してはいけないものが無いか確認しておく。
$ open /usr/local/var/mysql

MySQLのディレクトリ自体を削除。
$ sudo rm -rf /usr/local/var/mysql

5.7系を再インストールしてみたら、やっとログインできた!!!

5.7系をインストール
$ brew install mysql@5.7

$ mysql.server start              
Starting MySQL
. SUCCESS! 

$ mysql -u root                    
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.29 Homebrew

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

おわりに

やっぱり環境構築は大変だと改めて実感しました。。。
いい勉強にはなったので、もっと場数踏んで、環境構築を行う速度を上げたいものですね。

参照

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