| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

「MySQL」の版間の差分

提供: MyMemoWiki
ナビゲーションに移動 検索に移動
 
(同じ利用者による、間の32版が非表示)
7行目: 7行目:
 
==インストール==
 
==インストール==
 
===[[Windows]]===
 
===[[Windows]]===
 +
====5.6====
 
*[http://typea.info/blg/glob/2014/04/mysql56-windows-81.html Windows8.1にMySQL5.6をインストール]
 
*[http://typea.info/blg/glob/2014/04/mysql56-windows-81.html Windows8.1にMySQL5.6をインストール]
 +
====8.0====
 +
*[https://www.typea.info/blog/index.php/2022/02/03/mysql80_install_windows10/ Windows10 にMySQL8.0をインストール
 +
 
===[[Ubuntu]](apt-getでインストール)===
 
===[[Ubuntu]](apt-getでインストール)===
 
  $ sudo apt-get install mysql-server
 
  $ sudo apt-get install mysql-server
74行目: 78行目:
 
  # [[chkconfig]] | grep "mysql"
 
  # [[chkconfig]] | grep "mysql"
 
  mysql          0:off 1:off 2:on 3:on 4:on 5:on 6:off
 
  mysql          0:off 1:off 2:on 3:on 4:on 5:on 6:off
 +
===[[Mac]](brewからクライアントのみインストール)===
 +
<pre>
 +
$ brew install mysql-client
 +
</pre>
 +
*インストールログの末尾を参照してPATHを通す
 +
 
===権限の初期設定===
 
===権限の初期設定===
 
*http://dev.mysql.com/doc/refman/5.1-olh/ja/unix-post-installation.html
 
*http://dev.mysql.com/doc/refman/5.1-olh/ja/unix-post-installation.html
79行目: 89行目:
 
*http://dev.mysql.com/doc/refman/4.1/ja/resetting-permissions.html
 
*http://dev.mysql.com/doc/refman/4.1/ja/resetting-permissions.html
 
=====[[Ubuntu]] 初期パスワードの場所=====
 
=====[[Ubuntu]] 初期パスワードの場所=====
 +
----
 
*確認
 
*確認
 
<pre>
 
<pre>
170行目: 181行目:
  
 
====初期の権限変更ツール mysql_secure_installation====
 
====初期の権限変更ツール mysql_secure_installation====
 +
----
 
*初期パスワード /var/log/mysqld.log | grep "temporary password"
 
*初期パスワード /var/log/mysqld.log | grep "temporary password"
 
  # mysql_secure_installation  
 
  # mysql_secure_installation  
184行目: 196行目:
 
   
 
   
 
  Cleaning up...
 
  Cleaning up...
 +
 +
=====Failed! Error: SET PASSWORD has no significance for user... エラー=====
 +
----
 +
*上記「Ubuntu 初期パスワードの場所」のユーザーでログイン
 +
<pre>
 +
Estimated strength of the password: 100
 +
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y
 +
... Failed! Error: SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.
 +
</pre>
 +
*ループから抜け出せない、以下のプロンプトでCtrl+C
 +
<pre>
 +
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) :
 +
</pre>
 +
*https://dev.mysql.com/doc/refman/8.0/ja/resetting-permissions.html
 +
<pre>
 +
ubuntu@ip-172-26-11-57:~$ mysql -u debian-sys-maint -p
 +
Enter password:
 +
Welcome to the MySQL monitor.  Commands end with ; or \g.
 +
Your MySQL connection id is 9
 +
Server version: 8.0.30-0ubuntu0.20.04.2 (Ubuntu)
 +
 +
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
 +
 +
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> set password for 'root'@'localhost' = 'NewPassword';
 +
ERROR 4102 (HY000): SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.
 +
</pre>
 +
*以下で成功!
 +
<pre>
 +
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'NewPassword';
 +
Query OK, 0 rows affected (0.01 sec)
 +
</pre>
 +
 +
<pre>
 +
mysql> select version();
 +
+-------------------------+
 +
| version()              |
 +
+-------------------------+
 +
| 8.0.30-0ubuntu0.20.04.2 |
 +
+-------------------------+
 +
1 row in set (0.00 sec)
 +
</pre>
 +
 
===簡易設定===
 
===簡易設定===
 
====バージョンの確認====
 
====バージョンの確認====
450行目: 510行目:
 
*[[phpMyAdmin]]
 
*[[phpMyAdmin]]
  
==[[Tips]]==
+
===ポートフォワーディング===
===管理===
+
*ssh -i 踏み台サーバー鍵ファイル -L  ローカルポート:本当に接続したいサーバー:本当に接続したいサーバーのポート 踏み台サーバーユーザー@踏み台サーバー
====データファイルの場所====
+
<pre>
 +
$ ssh -i ~/.ssh/typea-dev-key.pem -L 13308:typea-dev-mysql-multiaz.c5ihdpszudfw.us-east-1.rds.amazonaws.com:3306 ec2-user@34.226.213.144
 +
</pre>
 +
RDSにEC2を踏み台にして、SQLWorkbentchから接続
 +
 
 +
[[File:port_forwarding.png|600px]]
 +
 
 +
==管理==
 +
===データファイルの場所===
 +
----
 
  /etc/my.cnf
 
  /etc/my.cnf
 
  datadir=/var/lib/mysql
 
  datadir=/var/lib/mysql
====テーブル一覧を表示====
+
===テーブル一覧を表示===
 +
----
 
  # mysql -u root -p  
 
  # mysql -u root -p  
 
   mysql&gt; use mt
 
   mysql&gt; use mt
474行目: 544行目:
 
  +-------------------+
 
  +-------------------+
 
  44 rows in set (0.00 sec)
 
  44 rows in set (0.00 sec)
====セッションの確認と切断====
+
===セッションの確認と切断===
 +
----
 
  show processlist;
 
  show processlist;
 
  kill [Id]
 
  kill [Id]
 +
==[[SQL]]==
 +
===カンマ区切り文字列をSplitする===
 +
    SUBSTRING_INDEX(comma_string,',',1),
 +
    SUBSTRING_INDEX(SUBSTRING_INDEX(comma_string,',',1),',',1),
 +
    SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(comma_string,',',1),',',1),',',1),
 +
    SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(comma_string,',',1),',',1),',',1),',',1)
 +
  
===[[SQL]]===
+
===制約を無視してテーブルをtruncateする===
====制約を無視してテーブルをtruncateする====
+
----
 
*一旦、FO[[R]]EIGN_KEY_CHECKSを0にする
 
*一旦、FO[[R]]EIGN_KEY_CHECKSを0にする
 
  mysql&gt; SET FO[[R]]EIGN_KEY_CHECKS=0;
 
  mysql&gt; SET FO[[R]]EIGN_KEY_CHECKS=0;
 
  mysql&gt; truncate table hoge;
 
  mysql&gt; truncate table hoge;
 
  mysql&gt; SET FO[[R]]EIGN_KEY_CHECKS=1;
 
  mysql&gt; SET FO[[R]]EIGN_KEY_CHECKS=1;
===mysqlコマンド===
+
 
====ソースファイルの[[SQL]]を実行====
+
===パーティショニング===
 +
----
 +
*[https://dev.mysql.com/doc/refman/5.6/ja/partitioning-types.html パーティションタイプ]
 +
*https://dev.mysql.com/doc/refman/5.6/ja/partitioning-range.html
 +
<pre>
 +
CREATE TABLE employees (
 +
    id INT NOT NULL,
 +
    fname VARCHAR(30),
 +
    lname VARCHAR(30),
 +
    hired DATE NOT NULL DEFAULT '1970-01-01',
 +
    separated DATE NOT NULL DEFAULT '9999-12-31',
 +
    job_code INT NOT NULL,
 +
    store_id INT NOT NULL
 +
)
 +
PARTITION BY RANGE (store_id) (
 +
    PARTITION p0 VALUES LESS THAN (6),
 +
    PARTITION p1 VALUES LESS THAN (11),
 +
    PARTITION p2 VALUES LESS THAN (16),
 +
    PARTITION p3 VALUES LESS THAN (21)
 +
);
 +
</pre>
 +
====リストパーティショニング====
 +
----
 +
*https://dev.mysql.com/doc/refman/5.6/ja/partitioning-list.html
 +
<pre>
 +
CREATE TABLE employees (
 +
    id INT NOT NULL,
 +
    fname VARCHAR(30),
 +
    lname VARCHAR(30),
 +
    hired DATE NOT NULL DEFAULT '1970-01-01',
 +
    separated DATE NOT NULL DEFAULT '9999-12-31',
 +
    job_code INT,
 +
    store_id INT
 +
)
 +
PARTITION BY LIST(store_id) (
 +
    PARTITION pNorth VALUES IN (3,5,6,9,17),
 +
    PARTITION pEast VALUES IN (1,2,10,11,19,20),
 +
    PARTITION pWest VALUES IN (4,12,13,14,18),
 +
    PARTITION pCentral VALUES IN (7,8,15,16)
 +
);
 +
</pre>
 +
*https://dev.mysql.com/doc/refman/5.6/ja/partitioning-columns-list.html
 +
<pre>
 +
CREATE TABLE customers_1 (
 +
    first_name VARCHAR(25),
 +
    last_name VARCHAR(25),
 +
    street_1 VARCHAR(30),
 +
    street_2 VARCHAR(30),
 +
    city VARCHAR(15),
 +
    renewal DATE
 +
)
 +
PARTITION BY LIST COLUMNS(city) (
 +
    PARTITION pRegion_1 VALUES IN('Oskarshamn', 'Högsby', 'Mönsterås'),
 +
    PARTITION pRegion_2 VALUES IN('Vimmerby', 'Hultsfred', 'Västervik'),
 +
    PARTITION pRegion_3 VALUES IN('Nässjö', 'Eksjö', 'Vetlanda'),
 +
    PARTITION pRegion_4 VALUES IN('Uppvidinge', 'Alvesta', 'Växjo')
 +
);
 +
</pre>
 +
 
 +
<pre>
 +
mysql> alter table jra_data
 +
    -> partition by list COLUMNS(data_type) (
 +
    -> partition p0 values in ('0'),
 +
    -> partition p1 values in ('1'),
 +
    -> partition p2 values in ('2'),
 +
    -> partition p5 values in ('5'),
 +
    -> partition p7 values in ('7'),
 +
    -> partition p9 values in ('9'),
 +
    -> partition pA values in ('A'),
 +
    -> partition pB values in ('B')
 +
    -> );
 +
</pre>
 +
*確認
 +
<pre>
 +
mysql> SELECT TABLE_SCHEMA, TABLE_NAME, PARTITION_NAME, PARTITION_ORDINAL_POSITION, TABLE_ROWS FROM INFORMATIO
 +
N_SCHEMA.PARTITIONS WHERE TABLE_NAME='jra_data';
 +
+--------------+------------+----------------+----------------------------+------------+
 +
| TABLE_SCHEMA | TABLE_NAME | PARTITION_NAME | PARTITION_ORDINAL_POSITION | TABLE_ROWS |
 +
+--------------+------------+----------------+----------------------------+------------+
 +
| jra          | jra_data  | p0            |                          1 |          8 |
 +
| jra          | jra_data  | p1            |                          2 |    533260 |
 +
| jra          | jra_data  | p2            |                          3 |      69894 |
 +
| jra          | jra_data  | p5            |                          4 |    459127 |
 +
| jra          | jra_data  | p7            |                          5 |    1052898 |
 +
| jra          | jra_data  | p9            |                          6 |      5694 |
 +
| jra          | jra_data  | pA            |                          7 |    707408 |
 +
| jra          | jra_data  | pB            |                          8 |      10085 |
 +
+--------------+------------+----------------+----------------------------+------------+
 +
8 rows in set (0.06 sec)
 +
 
 +
</pre>
 +
 
 +
==mysqlコマンド==
 +
===ソースファイルの[[SQL]]を実行===
 +
----
 
  \.&lt;ファイル名&gt;
 
  \.&lt;ファイル名&gt;
====データベースの変更====
+
===データベースの変更===
 +
----
 
  use
 
  use
====ヘルプ====
+
===ヘルプ===
 +
----
 
  help
 
  help
====テーブル定義を確認====
+
===テーブル定義を確認===
 +
----
 
  show create table テーブル名
 
  show create table テーブル名
====テーブル一覧====
+
===テーブル一覧===
 +
----
 
  show tables
 
  show tables
====ポートを調べる====
+
===ポートを調べる===
 +
----
 
  mysql&gt; show variables like 'port';
 
  mysql&gt; show variables like 'port';
 
  +---------------+-------+
 
  +---------------+-------+
508行目: 685行目:
 
*http://dev.mysql.com/downloads/connector/
 
*http://dev.mysql.com/downloads/connector/
 
===[[C#]]から接続===
 
===[[C#]]から接続===
 +
----
 
====DML(CREATE TABLE)====
 
====DML(CREATE TABLE)====
 +
----
 
<pre>
 
<pre>
 
using MySql.Data.MySqlClient;
 
using MySql.Data.MySqlClient;
544行目: 723行目:
  
 
=====データ登録(INSERT)=====
 
=====データ登録(INSERT)=====
 +
----
 
<pre>
 
<pre>
 
public void Load(string host, string database, string user,string password, string fileName)
 
public void Load(string host, string database, string user,string password, string fileName)
589行目: 769行目:
 
</pre>
 
</pre>
 
====データ取得(SELECT)====
 
====データ取得(SELECT)====
 +
----
 
<pre>
 
<pre>
 
  using MySql.Data.MySqlClient;
 
  using MySql.Data.MySqlClient;
601行目: 782行目:
 
         {
 
         {
 
             var pgm = new Program();
 
             var pgm = new Program();
             pgm.[[Access]]Test();             
+
             pgm.AccessTest();             
 
         }
 
         }
 
   
 
   
         public void [[Access]]Test()
+
         public void AccessTest()
 
         {
 
         {
             // Unable to convert [[MySQL]] date/time value to System.DateTime
+
             // Unable to convert MySQL date/time value to System.DateTime
 
             // https://stackoverflow.com/questions/2934844/unable-to-convert-mysql-date-time-value-to-system-datetime
 
             // https://stackoverflow.com/questions/2934844/unable-to-convert-mysql-date-time-value-to-system-datetime
             var conInfo = $"[[Database]]=wordpress;Data Source=192.168.0.2;User Id=root;Password={password}; pooling = false; convert zero datetime=True";
+
             var conInfo = $"Database=wordpress;Data Source=192.168.0.2;User Id=root;Password={password}; pooling = false; convert zero datetime=True";
 
              
 
              
 
             using(var conn = new MySqlConnection(conInfo))
 
             using(var conn = new MySqlConnection(conInfo))
633行目: 814行目:
 
     }
 
     }
 
  }
 
  }
 +
</pre>
 +
====データ取得(カーソル)====
 +
----
 +
<pre>
 +
using (var conn = new MySqlConnection(GetConnStr(host, database, user, password)))
 +
{
 +
    conn.Open();
 +
 +
    var command = new MySqlCommand("select * from jra_data", conn);
 +
    using(var reader = command.ExecuteReader())
 +
    {
 +
        while(reader.Read())
 +
        {
 +
            Debug.WriteLine(reader.GetString("data"));
 +
        }
 +
    }
 +
}
 
</pre>
 
</pre>
  

2023年11月13日 (月) 10:57時点における最新版

| XAMPP |

目次

MySQL

Database | CentOS |

インストール

Windows

5.6

8.0

Ubuntu(apt-getでインストール)

  1. $ sudo apt-get install mysql-server
  • 途中でパスワードの設定を求められる

0816 mysql password.png

CentOS(yumからインストール)

手順

  1. $ sudo yum localinstall mysql80-community-release-el7-3.noarch.rpm
  2. yum update
  3. $ sudo yum install mysql-community-server

ダウンロード

MySQL Community Server


アカウントの登録

  • mysql グループと mysqlユーザーの作成
  1. # groupadd mysql
  2. # useradd -g mysql mysql

解凍

  1. $ tar xvf MySQL-5.6.13-1.linux_glibc2.5.i386.rpm-bundle.tar

インストール

  • 標準の最低限のインストールには、サーバーとクライアント RPM をインストールします。
  • RPM はまた MySQL サーバーを運用するためのユーザー mysql (存在しない場合) のログインアカウントを作成する
  • サーバーがブート時に自動的に起動するように適切なエントリを /etc/init.d/ に作成する
  1. # rpm -ivh MySQL-shared-5.6.13-1.linux_glibc2.5.i386.rpm
  2. # rpm -ivh MySQL-shared-compat-5.6.13-1.linux_glibc2.5.i386.rpm
  3. # rpm -ivh MySQL-server-5.6.13-1.linux_glibc2.5.i386.rpm
  4. # rpm -ivh MySQL-client-5.6.13-1.linux_glibc2.5.i386.rpm

<blockquote>serverインストール時に、初期パスワードの情報がコンソールに出力される</blockquote>

  1. A random root password has been set. You will find it in '/root/.mysql_secret'.

<blockquote>もしくはログに出力されている</blockquote>

  1. /var/log/mysqld.log | grep "temporary password"
開発で必要(Djangoなど)
  1. # rpm -ivh MySQL-devel-5.6.13-1.linux_glibc2.5.i386.rpm

起動と停止

CentOS
  1. # /sbin/service mysql start
  2. Starting MySQL... [ OK ]
  3. # /etc/init.d/mysql stop
  4. Shutting down MySQL.. [ OK ]
CentOS7
  1. # systemctl enable mysqld
  2. # systemctl start mysqld
Ubuntu
  1. $ sudo /etc/init.d/mysql start
  2. $ sudo /etc/init.d/mysql stop
  3. $ sudo /etc/init.d/mysql restart
mysqld_safe(mysqld のラッパ)
  1. shell> cd mysql_installation_directory
  2. shell> bin/mysqld_safe &

起動設定がされたか確認

  1. # chkconfig | grep "mysql"
  2. mysql 0:off 1:off 2:on 3:on 4:on 5:on 6:off

Mac(brewからクライアントのみインストール)

  1. $ brew install mysql-client
  • インストールログの末尾を参照してPATHを通す

権限の初期設定

忘れたパスワードをリセット

Ubuntu 初期パスワードの場所

  • 確認
  1. $ sudo cat /etc/mysql/debian.cnf
  2. # Automatically generated for Debian scripts. DO NOT TOUCH!
  3. [client]
  4. host = localhost
  5. user = debian-sys-maint
  6. password = KJmv1zRL0acKBftn
  7. socket = /var/run/mysqld/mysqld.sock
  8. [mysql_upgrade]
  9. host = localhost
  10. user = debian-sys-maint
  11. password = KJmv1zRL0acKBftn
  12. socket = /var/run/mysqld/mysqld.sock
  • ログイン
  1. piroto@jinmu:/etc/mysql$ mysql -u debian-sys-maint -p
  2. Enter password:
  3. Welcome to the MySQL monitor. Commands end with ; or \g.
  4. Your MySQL connection id is 15
  5. Server version: 8.0.21-0ubuntu0.20.04.4 (Ubuntu)
  6. mysql> use mysql
  7. mysql> select User,Host,plugin from mysql.user;
  8. +------------------+-----------+-----------------------+
  9. | User | Host | plugin |
  10. +------------------+-----------+-----------------------+
  11. | debian-sys-maint | localhost | caching_sha2_password |
  12. | mysql.infoschema | localhost | caching_sha2_password |
  13. | mysql.session | localhost | caching_sha2_password |
  14. | mysql.sys | localhost | caching_sha2_password |
  15. | root | localhost | auth_socket |
  16. +------------------+-----------+-----------------------+
  17. 5 rows in set (0.00 sec)
  • rootパスワードの変更
  1. mysql> select version();
  2. +-------------------------+
  3. | version() |
  4. +-------------------------+
  5. | 8.0.21-0ubuntu0.20.04.4 |
  6. +-------------------------+
  7. 1 row in set (0.00 sec)
  8.  
  9. mysql> set password for 'root'@'localhost' = 'new password';
  10. Query OK, 0 rows affected, 1 warning (0.06 sec)
  • クライアントから root でログイン
    • sudo しないとERROR 1698 (28000): Access denied エラー となる
  1. $ mysql -u root -p
  2. Enter password:
  3. ERROR 1698 (28000): Access denied for user 'root'@'localhost'
  1. iroto@jinmu:/etc/mysql$ mysql -u root -p
  2. Enter password:
  3. ERROR 1698 (28000): Access denied for user 'root'@'localhost'
  4. piroto@jinmu:/etc/mysql$ sudo mysql -u root -p
  5. Enter password:
  6. Welcome to the MySQL monitor. Commands end with ; or \g.
  7. Your MySQL connection id is 26
  8. Server version: 8.0.21-0ubuntu0.20.04.4 (Ubuntu)
  9. mysql>
  10.  
mysqldを--skip-grant-tables オプションで起動
  1. # mysqld --skip-grant-tables &
mysqld サーバに接続
  1. # mysql -u root mysql
新しいパスワードの設定
  1. mysql> update user set Password=PASSWORD('newpassword')
  2. -> where User='root';
  3. Query OK, 4 rows affected (0.11 sec)
  4. Rows matched: 4 Changed: 4 Warnings: 0
  5.  
  6. mysql> flush privileges;
  7. Query OK, 0 rows affected (0.01 sec)
rootパスワードの変更
  1. mysql> set password for 'root'@'localhost' = password('newpassword');
  2. Query OK, 0 rows affected (0.00 sec)
パスワードの設定 MySQL8
  1. mysql> set password for 'wordpress'@'localhost' = 'your password';

初期の権限変更ツール mysql_secure_installation


  • 初期パスワード /var/log/mysqld.log | grep "temporary password"
  1. # mysql_secure_installation
  2. Change the root password? [Y/n] n
  3. Remove anonymous users? [Y/n] Y
  4. Disallow root login remotely? [Y/n] Y
  5. Remove test database and access to it? [Y/n] n
  6. Reload privilege tables now? [Y/n] Y
  7.  
  8. All done! If you've completed all of the above steps, your MySQL
  9. installation should now be secure.
  10.  
  11. Thanks for using MySQL!
  12.  
  13. Cleaning up...
Failed! Error: SET PASSWORD has no significance for user... エラー

  • 上記「Ubuntu 初期パスワードの場所」のユーザーでログイン
  1. Estimated strength of the password: 100
  2. Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y
  3. ... Failed! Error: SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.
  • ループから抜け出せない、以下のプロンプトでCtrl+C
  1. Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) :
  1. ubuntu@ip-172-26-11-57:~$ mysql -u debian-sys-maint -p
  2. Enter password:
  3. Welcome to the MySQL monitor. Commands end with ; or \g.
  4. Your MySQL connection id is 9
  5. Server version: 8.0.30-0ubuntu0.20.04.2 (Ubuntu)
  6.  
  7. Copyright (c) 2000, 2022, Oracle and/or its affiliates.
  8.  
  9. Oracle is a registered trademark of Oracle Corporation and/or its
  10. affiliates. Other names may be trademarks of their respective
  11. owners.
  12.  
  13. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  14.  
  15. mysql> set password for 'root'@'localhost' = 'NewPassword';
  16. ERROR 4102 (HY000): SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.
  • 以下で成功!
  1. mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'NewPassword';
  2. Query OK, 0 rows affected (0.01 sec)
  1. mysql> select version();
  2. +-------------------------+
  3. | version() |
  4. +-------------------------+
  5. | 8.0.30-0ubuntu0.20.04.2 |
  6. +-------------------------+
  7. 1 row in set (0.00 sec)

簡易設定

バージョンの確認

  1. mysql> select version();
  2. +-----------+
  3. | version() |
  4. +-----------+
  5. | 5.0.77 |
  6. +-----------+
  7. 1 row in set (0.00 sec)

MySQL 簡易設定

データベースの作成

作成

  1. # mysql -u root -p
  2. mysql> create database test_db default character set utf8;
  3. Query OK, 1 row affected (0.00 sec)
文字コード

確認

  1. mysql> show create database test_db;
  2. +----------+------------------------------------------------------------------+
  3. | Database | Create Database |
  4. +----------+------------------------------------------------------------------+
  5. | test_db | CREATE DATABASE `test_db` /*!40100 DEFAULT CHARACTER SET utf8 */ |
  6. +----------+------------------------------------------------------------------+
  7. 1 row in set (0.00 sec)

データベースの一覧

  1. mysql> show databases;
  2. +--------------------+
  3. | Database |
  4. +--------------------+
  5. | information_schema |
  6. | mysql |
  7. | performance_schema |
  8. | song_dict |
  9. | sys |
  10. +--------------------+
  11. 5 rows in set (0.00 sec)

権限

  • 接続を許可するユーザーをmysqlデータベース内で管理している
  • ユーザーがアクセスする際にはアクセス元のホスト(IPアドレス)もセットで認証が行われる

権限テーブル

テーブル名 説明
user ユーザーの基本的な定義
host ホストに対する権限の定義
db データベースに対する権限の定義
tables_priv テーブルに対する権限の定義
clumuns_priv カラムに対する権限の定義

ユーザーの作成

  1. mysql> create user test_user@localhost identified by 'new password';
  2. Query OK, 0 rows affected (0.03 sec)

権限の付与

限定して付与
  1. mysql> grant create,alter,select,insert,update,delete,index on *.* to test_user@localhost;
  2. Query OK, 0 rows affected (0.00 sec)
管理権限を付与
  • test_admin@localhost を作成した上で管理権限を付与
  • リモートアクセスを可能とするには、test_admin@localhost の部分を test_admin@'%' とする
  1. mysql> grant all privileges on *.* to test_admin@localhost identified by 'newpassword' with grant option;
  2. Query OK, 0 rows affected (0.00 sec)

外部から接続

ポートを開ける

  1. # firewall-cmd --permanent --zone=public --add-port=3306/tcp
  2. # firewall-cmd --reload
  1. piroto@jinmu:~$ sudo ufw allow 3306
  2. ルールを追加しました
  3. ルールを追加しました (v6)
  4. piroto@jinmu:~$ sudo ufw status
  5. 状態: アクティブ
  6.  
  7. To Action From
  8. -- ------ ----
  9. 80 ALLOW Anywhere
  10. 3306 ALLOW Anywhere
  11. 80 (v6) ALLOW Anywhere (v6)
  12. 3306 (v6) ALLOW Anywhere (v6)

root@%を追加

確認
  1. mysql> select user,host from mysql.user;
  2. +------------------+-----------+
  3. | user | host |
  4. +------------------+-----------+
  5. | mysql.infoschema | localhost |
  6. | mysql.session | localhost |
  7. | mysql.sys | localhost |
  8. | pma | localhost |
  9. | root | localhost |
  10. | wordpress | localhost |
  11. +------------------+-----------+
ユーザーの追加
  1. mysql> create user 'root'@'%' identified by 'パスワード';
  2. mysql> set password for 'root'@'%' = 'パスワード';
  3. mysql> grant all on *.* to 'root'@'%';
確認
  1. mysql> select user, host from user;
  2. +------------------+-----------+
  3. | user | host |
  4. +------------------+-----------+
  5. | root | % |
  6. | mysql.infoschema | localhost |
  7. | mysql.session | localhost |
  8. | mysql.sys | localhost |
  9. | pma | localhost |
  10. | root | localhost |
  11. | wordpress | localhost |
  12. +------------------+-----------+

バックアップとリストア

mysqldump

  • 通常mysqldumpコマンドを使用する
  • データをテキストファイルとしてダンプするというシンプルな仕組みのコマンド
  • CREATE TABLE および INSERT文として出力される

テーブル名を指定してダンプ

  1. mysqldump [オプション] データベース名 [テーブル名 ...]

複数のデータベースを対象とする

  1. mysqldump [オプション] --databases [オプション] データベース名 [データベース名 ...]

すべてのデータベースを対象とする

  1. mysqldump [オプション] --all-databases [オプション]

バックアップ

  • DBすべて
  1. $ mysqldump --default-character-set=utf8 -u USER_NAME -p DB_NAME > OUTPUT_FILE.sql
  2. Enter password:
  • テーブル指定
  1. $ mysqldump -u USER_NAME -p -h HOST_NAME -t DB_NAME TABLE_NAME > OUTPUT_FILE.sql

レストア例

  • mysqldumpの出力はSQL文の羅列であるため、復元するにはリダイレクトを使ってmysqlに結果を与えれば良い
  1. # mysql -u root -p mt < mt_backup20140120.sql

接続

外部接続

Ubuntu エラー 111で接続できない

  1. $ msyql -u hoge -p -h 192.168.0.43 foo_db
  2. Can't connect to MySQL server on '192.168.0.43' (111)
  • localhostのみをリッスンしている
  • 設定ファイルを編集
  1. $ sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
  • bind-address =127.0.0.1 に制限されているためコメントアウト
  1. # If MySQL is running as a replication slave, this should be
  2. # changed. Ref https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_tmpdir
  3. # tmpdir = /tmp
  4. #
  5. # Instead of skip-networking the default is now to listen only on
  6. # localhost which is more compatible and is not less secure.
  7. # bind-address = 127.0.0.1
  • 再起動
  1. $ sudo systemctl restart mysql

Python

Install

  1. $ pip install --upgrade pip

Insert

  1. import mysql.connector
  2.  
  3. def ins():
  4. add_song_element = ("INSERT INTO song_element "
  5. "(element, reading, reading_rev) "
  6. "VALUES (%s, %s, %s)")
  7.  
  8. config = {
  9. 'user':'song_dict',
  10. 'password':'my password',
  11. 'host':'192.168.0.43',
  12. 'database':'song_dict'
  13. }
  14.  
  15. try:
  16. cnx = mysql.connector.connect(**config)
  17. cursor = cnx.cursor()
  18. cursor.execute(add_song_element, ('hoge', 'foo', 'bar'))
  19. except Exception as ee:
  20. print(ee)

Query

  1. query = ("SELECT id FROM song_element "
  2. "WHERE reading=%s and element=%s")
  3.  
  4. cnx = mysql.connector.connect(**config)
  5. cursor = cnx.cursor()
  6. cursor.execute(query , ('hoge', 'foo'))
  7. for (id) in cursor:
  8. print(id)

Java

  1. package info.typea.songdict.sample;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6.  
  7. public class DbAccess {
  8. public void doWork() {
  9. try (Connection conn = DriverManager.getConnection(
  10. "jdbc:mysql://hostname/dbname",
  11. "username",
  12. "password")) {
  13.  
  14. Statement stmt = conn.createStatement();
  15. ResultSet resultSet
  16. = stmt.executeQuery("select substr(reading,1,2) from song_element group by substr(reading,1,2)");
  17. while (resultSet.next()) {
  18. System.out.println(resultSet.getString(1));
  19. }
  20.  
  21. } catch(Exception e) {
  22. System.out.println(String.format("ERROR : %s", e));
  23. }
  24. }
  25. }

phpMyAdmin

ポートフォワーディング

  • ssh -i 踏み台サーバー鍵ファイル -L ローカルポート:本当に接続したいサーバー:本当に接続したいサーバーのポート 踏み台サーバーユーザー@踏み台サーバー
  1. $ ssh -i ~/.ssh/typea-dev-key.pem -L 13308:typea-dev-mysql-multiaz.c5ihdpszudfw.us-east-1.rds.amazonaws.com:3306 ec2-user@34.226.213.144

RDSにEC2を踏み台にして、SQLWorkbentchから接続

Port forwarding.png

管理

データファイルの場所


  1. /etc/my.cnf
  2. datadir=/var/lib/mysql

テーブル一覧を表示


  1. # mysql -u root -p
  2. mysql> use mt
  3. Reading table information for completion of table and column names
  4. You can turn off this feature to get a quicker startup with -A
  5.  
  6. Database changed
  7. mysql> show tables;
  8. +-------------------+
  9. | Tables_in_mt |
  10. +-------------------+
  11. | mt_asset |
  12. | mt_asset_meta |
  13. | mt_association |
  14. | mt_ts_funcmap |
  15. | mt_ts_job |
  16. +-------------------+
  17. 44 rows in set (0.00 sec)

セッションの確認と切断


  1. show processlist;
  2. kill [Id]

SQL

カンマ区切り文字列をSplitする

  1. SUBSTRING_INDEX(comma_string,',',1),
  2. SUBSTRING_INDEX(SUBSTRING_INDEX(comma_string,',',1),',',1),
  3. SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(comma_string,',',1),',',1),',',1),
  4. SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(comma_string,',',1),',',1),',',1),',',1)


制約を無視してテーブルをtruncateする


  • 一旦、FOREIGN_KEY_CHECKSを0にする
  1. mysql> SET FOREIGN_KEY_CHECKS=0;
  2. mysql> truncate table hoge;
  3. mysql> SET FOREIGN_KEY_CHECKS=1;

パーティショニング


  1. CREATE TABLE employees (
  2. id INT NOT NULL,
  3. fname VARCHAR(30),
  4. lname VARCHAR(30),
  5. hired DATE NOT NULL DEFAULT '1970-01-01',
  6. separated DATE NOT NULL DEFAULT '9999-12-31',
  7. job_code INT NOT NULL,
  8. store_id INT NOT NULL
  9. )
  10. PARTITION BY RANGE (store_id) (
  11. PARTITION p0 VALUES LESS THAN (6),
  12. PARTITION p1 VALUES LESS THAN (11),
  13. PARTITION p2 VALUES LESS THAN (16),
  14. PARTITION p3 VALUES LESS THAN (21)
  15. );

リストパーティショニング


  1. CREATE TABLE employees (
  2. id INT NOT NULL,
  3. fname VARCHAR(30),
  4. lname VARCHAR(30),
  5. hired DATE NOT NULL DEFAULT '1970-01-01',
  6. separated DATE NOT NULL DEFAULT '9999-12-31',
  7. job_code INT,
  8. store_id INT
  9. )
  10. PARTITION BY LIST(store_id) (
  11. PARTITION pNorth VALUES IN (3,5,6,9,17),
  12. PARTITION pEast VALUES IN (1,2,10,11,19,20),
  13. PARTITION pWest VALUES IN (4,12,13,14,18),
  14. PARTITION pCentral VALUES IN (7,8,15,16)
  15. );
  1. CREATE TABLE customers_1 (
  2. first_name VARCHAR(25),
  3. last_name VARCHAR(25),
  4. street_1 VARCHAR(30),
  5. street_2 VARCHAR(30),
  6. city VARCHAR(15),
  7. renewal DATE
  8. )
  9. PARTITION BY LIST COLUMNS(city) (
  10. PARTITION pRegion_1 VALUES IN('Oskarshamn', 'Högsby', 'Mönsterås'),
  11. PARTITION pRegion_2 VALUES IN('Vimmerby', 'Hultsfred', 'Västervik'),
  12. PARTITION pRegion_3 VALUES IN('Nässjö', 'Eksjö', 'Vetlanda'),
  13. PARTITION pRegion_4 VALUES IN('Uppvidinge', 'Alvesta', 'Växjo')
  14. );
  1. mysql> alter table jra_data
  2. -> partition by list COLUMNS(data_type) (
  3. -> partition p0 values in ('0'),
  4. -> partition p1 values in ('1'),
  5. -> partition p2 values in ('2'),
  6. -> partition p5 values in ('5'),
  7. -> partition p7 values in ('7'),
  8. -> partition p9 values in ('9'),
  9. -> partition pA values in ('A'),
  10. -> partition pB values in ('B')
  11. -> );
  • 確認
  1. mysql> SELECT TABLE_SCHEMA, TABLE_NAME, PARTITION_NAME, PARTITION_ORDINAL_POSITION, TABLE_ROWS FROM INFORMATIO
  2. N_SCHEMA.PARTITIONS WHERE TABLE_NAME='jra_data';
  3. +--------------+------------+----------------+----------------------------+------------+
  4. | TABLE_SCHEMA | TABLE_NAME | PARTITION_NAME | PARTITION_ORDINAL_POSITION | TABLE_ROWS |
  5. +--------------+------------+----------------+----------------------------+------------+
  6. | jra | jra_data | p0 | 1 | 8 |
  7. | jra | jra_data | p1 | 2 | 533260 |
  8. | jra | jra_data | p2 | 3 | 69894 |
  9. | jra | jra_data | p5 | 4 | 459127 |
  10. | jra | jra_data | p7 | 5 | 1052898 |
  11. | jra | jra_data | p9 | 6 | 5694 |
  12. | jra | jra_data | pA | 7 | 707408 |
  13. | jra | jra_data | pB | 8 | 10085 |
  14. +--------------+------------+----------------+----------------------------+------------+
  15. 8 rows in set (0.06 sec)
  16.  

mysqlコマンド

ソースファイルのSQLを実行


  1. \.<ファイル名>

データベースの変更


  1. use

ヘルプ


  1. help

テーブル定義を確認


  1. show create table テーブル名

テーブル一覧


  1. show tables

ポートを調べる


  1. mysql> show variables like 'port';
  2. +---------------+-------+
  3. | Variable_name | Value |
  4. +---------------+-------+
  5. | port | 3306 |
  6. +---------------+-------+
  7. 1 row in set (0.00 sec)

プログラミング

JDBC Download

C#から接続


DML(CREATE TABLE)


  1. using MySql.Data.MySqlClient;
  2. using System.Data;
  3. using System.Diagnostics;
  4.  
  5. public void CreateTable(string host, string database, string user, string password)
  6. {
  7. // create database jra default character set utf8;
  8. // create user 'jra'@'localhost' identified by 'new password';
  9. // create user 'jra'@'%' identified by 'new password';
  10. // grant all privileges on *.* to 'jra'@'%' with grant option;
  11.  
  12. var conInfo = $"Database=jra;Data Source=192.168.0.2;User Id=jra;Password=password; pooling = false; convert zero datetime=True";
  13. using (var conn = new MySqlConnection(conInfo))
  14. {
  15. conn.Open();
  16.  
  17. var createTable = @"
  18. create table jra_data (
  19. rec_spec varchar(2) not null,
  20. rec_key varchar(100) not null,
  21. make_date varchar(10) not null,
  22. data_type varchar(1) not null,
  23. data mediumtext,
  24. primary key(rec_spec, rec_key)
  25. )";
  26. var cmd = new MySqlCommand(createTable);
  27. cmd.Connection = conn;
  28. cmd.ExecuteNonQuery();
  29. }
  30. }
データ登録(INSERT)

  1. public void Load(string host, string database, string user,string password, string fileName)
  2. {
  3.  
  4. MySqlCommand insCmd =
  5. new MySqlCommand(
  6. @"insert into jra_data ( rec_spec, rec_key, make_date, data_type, data ) " +
  7. " values ( @rec_spec, @rec_key, @make_date, @data_type, @data )");
  8.  
  9. var conInfo = $"Database=jra;Data Source=192.168.0.2;User Id=jra;Password=password; pooling = false; convert zero datetime=True";
  10. using (var conn = new MySqlConnection(conInfo))
  11. {
  12. conn.Open();
  13.  
  14. insCmd.Connection = conn;
  15.  
  16. using (var reader = new StreamReader(fileName))
  17. {
  18. string line = null;
  19. while ((line = reader.ReadLine()) != null)
  20. {
  21. var record = line.Split("\t");
  22. Debug.WriteLine(line);
  23. if (record.Length >= 5)
  24. {
  25. var recSpec = record[0];
  26. var makeDate = record[1];
  27. var dataType = record[2];
  28. var recKey = record[3];
  29. var data = record[4];
  30.  
  31. insCmd.Parameters.Clear();
  32. insCmd.Parameters.Add(new MySqlParameter("rec_spec", recSpec));
  33. insCmd.Parameters.Add(new MySqlParameter("rec_key", recKey));
  34. insCmd.Parameters.Add(new MySqlParameter("make_date", makeDate));
  35. insCmd.Parameters.Add(new MySqlParameter("data_type", dataType));
  36. insCmd.Parameters.Add(new MySqlParameter("data", data));
  37. insCmd.ExecuteNonQuery();
  38. }
  39. }
  40. }
  41. }
  42. }

データ取得(SELECT)


  1. using MySql.Data.MySqlClient;
  2. using System;
  3. using System.Data;
  4. namespace Mt2Wp
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. var pgm = new Program();
  11. pgm.AccessTest();
  12. }
  13. public void AccessTest()
  14. {
  15. // Unable to convert MySQL date/time value to System.DateTime
  16. // https://stackoverflow.com/questions/2934844/unable-to-convert-mysql-date-time-value-to-system-datetime
  17. var conInfo = $"Database=wordpress;Data Source=192.168.0.2;User Id=root;Password={password}; pooling = false; convert zero datetime=True";
  18. using(var conn = new MySqlConnection(conInfo))
  19. {
  20. conn.Open();
  21. var da = new MySqlDataAdapter("select * from wp_posts", conn);
  22. var ds = new DataSet();
  23. da.Fill(ds);
  24. foreach (DataTable table in ds.Tables)
  25. {
  26. foreach (DataRow row in table.Rows)
  27. {
  28. foreach (DataColumn col in table.Columns)
  29. {
  30. Console.Write($"{row[col]}\t");
  31. }
  32. Console.WriteLine("");
  33. }
  34. }
  35. }
  36. }
  37. }
  38. }

データ取得(カーソル)


  1. using (var conn = new MySqlConnection(GetConnStr(host, database, user, password)))
  2. {
  3. conn.Open();
  4.  
  5. var command = new MySqlCommand("select * from jra_data", conn);
  6. using(var reader = command.ExecuteReader())
  7. {
  8. while(reader.Read())
  9. {
  10. Debug.WriteLine(reader.GetString("data"));
  11. }
  12. }
  13. }

Pythonから接続

  • requirements.txt
  1. mysql-connector-python==8.0.21
  1. def normalize(
  2. out_base_dir,
  3. norm_prefix,
  4. parse_dir,
  5. parse_prefix,
  6. skip_when_exists=True,
  7. host='localhost'):
  8.  
  9. add_song_element = ("INSERT INTO song_element "
  10. "(element, reading, reading_rev) "
  11. "VALUES (%s, %s, %s)")
  12. query = ("SELECT id FROM song_element "
  13. "WHERE reading=%s and element=%s")
  14.  
  15. config = {
  16. 'user':'song_dict',
  17. 'password':'',
  18. 'host':host,
  19. 'database':'song_dict'
  20. }
  21.  
  22. try:
  23. cnx = mysql.connector.connect(**config)
  24. cursor = cnx.cursor()
  25. cnt = 0;
  26. hashids = Hashids(salt=HASH_IDS_SALT)
  27. os.makedirs(out_base_dir, exist_ok=True)
  28. for file in glob.glob(os.path.join(parse_dir, '{0}*'.format(parse_prefix))):
  29. key = file.split(parse_prefix)[-1]
  30. print(key)
  31. with open(file, 'r') as inf:
  32. for l in inf.readlines():
  33. try:
  34. el = l.split('\t')
  35. meta = el[-1].split(',')
  36. element = el[0].strip()
  37. reading = meta[-2].strip()
  38. reading_rev = "".join(reversed(reading))
  39.  
  40. if element and len(element) > 1:
  41. cursor.execute(query , (reading, element))
  42. is_skip = False
  43. for (id) in cursor:
  44. is_skip = True
  45. break;
  46. if not is_skip:
  47. cursor.execute(add_song_element, (element, reading, reading_rev))
  48. print("{s} : {s}".format(cursor.lastrowid, el))
  49. except Exception as ee:
  50. print(ee)
  51. cnx.commit()
  52. except Exception as e:
  53. print(e)
  54. else:
  55. cnx.close()
  56.