情報システム科



データベース(MySQL)を使おう

データベース(MySQL)を使おう

目次

ローカルで使う ・  MySQL ・  DBI ・ 
リモートで使う ・  MySQL ・  phpMyAdmin ・  SSH ・  DBI ・ 


データベースの設計

MySQLをローカルで使う

MySQLを使えるようにする

参考
WindowsでMySQL
MySQLインストール完全ガイド

Downloads→MySQL 3.23→Standard binary RPMs
SETUP.EXEを実行すると
「16ビット MS-DOS サブシステム:config.ntシステムファイルは、MS-DOSおよびMicrosoft Windowdアプリケーションを実行するのに適していません」
これは、config.ntが存在しない場合もしくは正しくないものに書き換えられた場合に発生するため、次の手順で回復する。
Missing COMMAND.COM Causes Hidden Console Errorに説明があります。
具体的には、
MS-DOSで、以下のコマンドを実行。
cd %systemroot%\system32
copy *.nt *.bknt
cd ..
cd i386
expand config.nt_ %systemroot%\system32\config.nt
expand autoexec.nt_ %systemroot%\system32\autoexec.nt
expand command.co_ %systemroot%\system32\command.com

mysqld mysqlサーバをバックグラウンド起動
>mysqld --default-character-set=sjis

root(windowsのadministraterと同じ)のパスワード設定
>mysqladmin -u root password パスワード

mysqlサーバをシャットダウン
>mysqladmin -u root -p shutdown
Enter password: パスワード

mysql クライアントの起動
>mysql -u root -p
Enter password: パスワード
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 3.23.55-max-debug
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>

helpを表示
mysql> help

mysql クライアントの終了
mysql> \q
Bye

mysqlのヘルプを見る
>mysql -h

データベースをCREATE
mysql> CREATE DATABASE データベース名;
Query OK, 1 row affected (0.00 sec)

使用するデータベースを決める
mysql> USE データベース名;
Database changed

テーブルを作る
mysql> CREATE TABLE テーブル名 (id INTEGER UNIQUE NOT NULL,name CHAR(10) NOT NULL);
Query OK, 0 rows affected (0.00 sec)

現在、存在するテーブルを見る
mysql> show tables;
+--------------------------+
| Tables_in_データベース名 |
+--------------------------+
| テーブル名               |
+--------------------------+
1 row in set (0.02 sec)
データのINSERT
mysql> INSERT INTO テーブル名 VALUES (101,'black');
Query OK, 1 row affected (0.00 sec)
mysql> select * from テーブル名;
+-----+-------+
| id  | name  |
+-----+-------+
| 101 | black |
+-----+-------+
1 row in set (0.00 sec)

ローカルでDBIを使ってMySQLを使う

DBIとは
                      
   -------          |   |---|Mysqlドライバ     |---|MySQL     |
  |program|         |   | 
  | Perl |  |   |  |   |---|PostgreSQLドライバ|---|PostgreSQL| 
  | PHP   |--|API|--|DBI|
  | ・・・・  |  |   |  |   |---|オラクルドライバ  |---|オラクル  |  
   -------          |   |...
DBI(データベース・インタフェイス)はプログラミング言語からデータベースにアクセスするためのAPI(アプリケーション・プログラム・インターフェース)で、データベースにアクセスするための手段と、データベースの種類に依存しないインターフェイスを提供します。データベースの種類に依存しないということは、どのデータベースも同じ方法で操作することができるということです。MySQL、PostgreSQL、オラクル、他のデータベースに接続するときも、DBMS の基本構造を知る必要はありません。DBI によって定義されている API だけをマスターすればよいのです。
例えば、Perlスクリプトを
MySQLではなくPostgreSQLとの連携に変更したい場合は、
$db = DBI->connect('DBI:mysql:データベース名:サーバ名', ユーザー名, パスワード);

$db = DBI->connect('DBI:Pg:データベース名:サーバ名', ユーザー名, パスワード);
のように置き換えるだけです。

DBI,DBDのインストール
C:\Perl>ppm
PPM interactive shell (2.2.0) - type 'help' for available commands.

DBIのインストール
PPM> install DBI
Install package 'DBI?' (y/N): y
Installing package 'DBI'...
Downloading http://ppm.ActiveState.com/PPMPackages/5.6plus/MSWin32-x86-multi-thread/DBI.tar.gz ...
Installing C:\Perl\site\lib\auto\DBI\dbd_xsh.h
Installing C:\Perl\site\lib\auto\DBI\DBI.bs
Installing C:\Perl\site\lib\auto\DBI\DBI.dll
・・・・・・・・・・・・・・・・・

DBDのインストール
PPM> install DBD-mysql
Install package 'DBD-mysql?' (y/N): y
Installing package 'DBD-mysql'...
Error installing package 'DBD-mysql': Read a PPD for 'DBD-mysql', but it is not intended for this build of Perl (MSWin32-x86-multi-thread)
と、エラーとなる。
http://ppm.activestate.com/PPMPackages/zips/6xx-builds-only/
から
DBD-Mysql.zipを解凍し、C:\Perlへコピー
C:\Perl>ppm install DBD-mysql.ppd
Installing package 'DBD-mysql.ppd'...
Installing C:\Perl\site\lib\auto\DBD\mysql\mysql.bs
Installing C:\Perl\site\lib\auto\DBD\mysql\mysql.dll
・・・・・・・・・・


DBIクイックコマンド
メソッド
connect   データベースサーバと接続する 
disconnect データベースサーバとの接続を切る 
prepare    SQL文を設定する 
execute   設定されたSQL文を実行する 
do      SQL文を設定し、実行する 
quote      挿入するためのクォート文字、または BLOB 値 
fetch    フィールドの配列参照として次の行を取り出す。最速。 
fetchrow_array  フィールドの配列として次の行を取り出す。簡単。 
fetchrow_hashref ハッシュテーブルへの参照として次の行を取り出す。便利。 
例として、テーブルを作り、レコードを2つ追加し、全レコードを表示し、最後にテーブルを削除する、を作る

例の出力
>perl ***.cgi
Content-type: text/html

101 black
102 sweet


例のソース
#!/usr/local/bin/perl
print "Content-type: text/html\n\n";
use DBI;
$db = DBI->connect('DBI:mysql:データベース名:localhost','','')
            or print "データベースにつながりません<br>\n$DBI::errstr<br>";
$sth = $db->prepare("CREATE TABLE テーブル名 (id INTEGER UNIQUE NOT NULL,name CHAR(10) NOT NULL)"); #テーブルの作成
$sth->execute(); #実行
$sth = $db->prepare("INSERT INTO テーブル名 VALUES (101,'black')"); #レコードの追加
$sth->execute(); #実行
$sth = $db->prepare("INSERT INTO テーブル名 VALUES (102,'sweet')"); #レコードの追加
$sth->execute(); #実行

$sth = $db->prepare("SELECT * FROM テーブル名"); #レコードの抽出
$sth->execute(); #実行
$num = $sth->rows();
for( $i=0;$i<$num;$i++)
{
    @str = $sth->fetchrow_array();
    print ("$str[0]\t$str[1]<br>\n");
}
$sth = $db->prepare("DROP TABLE テーブル名"); #テーブルを削除
$sth->execute(); #実行
$sth->finish;
$db->disconnect;

Mysqlを使ってリモートで使う

サーバーへの接続 −−−つながらない
>mysql --host=s27.xrea.com --user=*** -p
Enter password: ************
ERROR 1130: Host 'YahooBB****.bbtec.net' is not allowed to connect to this MySQL server

今の環境では、
mysqlから、XREA.comのリモートサーバーのmysqlサーバーにつながらないので、別の方法を探す。

phpMyAdmin を使う


phpMyAdmin を使う。
phpMyAdminを使うとブラウザ上からMySQLのDB管理が可能となり、なかなか便利なツール。
参考
The phpMyAdmin projectのページ
phpMyAdmin-2.x.x-php.zip
phpMyAdminディレクトリを丸ごとshared_htmlにアップロード。
パーミッションはプロバイダ推奨のものに変更
phpMyAdmin//config.inc.phpを変更
$cfg['PmaAbsoluteUri'] = ''; を
$cfg['PmaAbsoluteUri'] = 'http://ユーザID.s?.xrea.com:8080/phpMyAdmin/';
に置き換え
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$$cfg['Servers'][$i]['only_db'] = '';

$cfg['Servers'][$i]['auth_type'] = 'http';
$cfg['Servers'][$i]['user'] = 'ユーザID';
$cfg['Servers'][$i]['password'] = 'XREAのパスワード';
$cfg['Servers'][$i]['only_db'] = 'ユーザID';
に置き換え
$cfg['DefaultLang'] = 'en'; を
$cfg['DefaultLang'] = 'ja'; に置き換え
保存してアップロード
http://ユーザID.s?.xrea.com:8080/phpMyAdmin/
にアクセスすると、HTTP認証が表示される
ユーザ名とパスワードを入力すれば完了

Sデータベースへアクセス

大変、使いやすいです。お勧めです。


SSH TeraTermPROを使う

暗号化された telnet である SSH を使い、サーバー側のクライアントソフトを使う

参考
SSH TeraTermPRO
TeraTermPRO


SSHクライアントであるTTSSH を使ってmysqlへアクセス例
XREA.COMへの接続
rbash-2.05a$ mysql -u ***** -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is **** to server version: 3.23.54

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> help

MySQL commands:
Note that all text commands must be first on line and end with ';'
help    (\h)    Display this help.
?       (\?)    Synonym for `help'.
clear   (\c)    Clear command.
connect (\r)    Reconnect to the server. Optional arguments are db and host.
edit    (\e)    Edit command with $EDITOR.
ego     (\G)    Send command to mysql server, display result vertically.
exit    (\q)    Exit mysql. Same as quit.
go      (\g)    Send command to mysql server.
nopager (\n)    Disable pager, print to stdout.
notee   (\t)    Don't write into outfile.
pager   (\P)    Set PAGER [to_pager]. Print the query results via PAGER.
print   (\p)    Print current command.
quit    (\q)    Quit mysql.
rehash  (\#)    Rebuild completion hash.
source  (\.)    Execute a SQL script file. Takes a file name as an argument.
status  (\s)    Get status information from the server.
tee     (\T)    Set outfile [to_outfile]. Append everything into given outfile.
use     (\u)    Use another database. Takes database name as argument.

Connection id: ****  (Can be used with mysqladmin kill)

mysql> status
--------------
mysql  Ver 11.18 Distrib 3.23.54, for pc-linux (i686)

Connection id:          *****
Current database:
Current user:           ******@localhost
Current pager:          stdout
Using outfile:          ''
Server version:         3.23.54
Protocol version:       10
Connection:             Localhost via UNIX socket
Client characterset:    ujis
Server characterset:    ujis
UNIX socket:            /tmp/mysql.sock
Uptime:                 5 days 21 hours 47 min 46 sec

Threads: 11  Questions: 3875064  Slow queries: 62  Opens: 2688311  Flush tables:
 1  Open tables: 4 Queries per second avg: 7.591
--------------

mysql> use ******
Database changed
mysql> show tables;
+----------------------+
| Tables_in_********   |
+----------------------+
| test                 |
+----------------------+
1 row in set (0.02 sec)

mysql> select * from test;
+-----+--------+
| id  | name   |
+-----+--------+
| 101 | tokyo  |
| 102 | oosaka |
+-----+--------+
2 rows in set (0.02 sec)

mysql> quit
Bye
rbash-2.05a$





SSHクライアントであるTTSSH を使ってPostgreSQへアクセス例
BBzone.NET
Last login: Tue Feb 25 14:17:39 2003 from yahoobb*****
 ****  ****   Since 2002.9              *   * ***** *****
 *   * *   *               Welcome to   **  * *       *
 *   * *   * *****  ***  ****   ***     * * * *       *
 ****  ****      * *   * *   * *   *    * * * ****    *
 *   * *   *    *  *   * *   * *****    * * * *       *
 *   * *   *  *    *   * *   * *     ** *  ** *       *
 ****  ****  *****  ***  *   *  ***  ** *   * *****   *

tanoshii:>psql   #PostgreSQLを使う

Welcome to psql, the PostgreSQL interactive terminal.
Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help on internal slash commands
       \g or terminate with semicolon to execute query
       \q to quit

tanoshii=> create table meibo2 (name char(16)); #テーブルの作成
CREATE
tanoshii=> insert into meibo2 values ('tokyo'); #データの追加
INSERT 53154 1
tanoshii=> insert into meibo2 values ('oosaka');
INSERT 53155 1
tanoshii=> select * from meibo2;        #データの表示
       name
------------------
 tokyo
 oosaka
(2 rows)

psqlコマンド一覧
\? 	psqlコマンドの一覧を表示する 
\h 	SQLコマンドの一覧を表示する 
\h 	SQLコマンド名 SQLコマンドの使い方を表示する 
\l 	データベースの一覧を表示する 
\dt 	表の一覧を表示する 
\d 	表名 表の項目一覧を表示する 
\dT 	項目の型の一覧を表示する 
\dS 	システム表の一覧を表示する 
\copy 	table {from | to} ファイル名 表をファイルにコピーする 
\i 	ファイル名 指定したファイル内のSQLを実行する 
\! 	OSコマンド OSのコマンドを実行する 
\q 	psqlを終了する 

リモートでDBIを使う

結果が、ローカルでわかるように、HTMLの出力を出す
例として、テーブルを作り、レコードを2つ追加し、全レコードを表示し、最後にテーブルを削除する、を作る

例の出力
101 black
102 sweet


例のcgiの内容は、 ローカルからDBIを使う と、同じ。
但し
use DBI;
$db = DBI->connect('DBI:mysql:データベース名:localhost','','')
            or print "データベースにつながりません<br>\n$DBI::errstr<br>";
use DBI;
$db = DBI->connect('DBI:mysql:データベース名:localhost','ユーザー名','パスワード')
            or print "データベースにつながりません<br>\n$DBI::errstr<br>";
と変える。




データベースの設計

データベース名:**** テーブル名:




ホームへ