0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Perl 6Advent Calendar 2015

Day 10

Perl6でDBに接続する

Last updated at Posted at 2015-12-10

こんばんは :whale2:
Perl 6 Advent Calendar 2015の10日目です。

DBIish でDBに接続してみようと思います。

ローカルに mariadb のインストール

手元のMacにhomebrewでmariadbをインストールします。

# インストール
$ brew install mariadb

# 起動
$ mysql.server start

# セキュリティ設定
$ mysql_secure_installation
## root のパスワードを root にしました(セキュリティ設定とは一体)

# データベース作成
$ mysql -uroot -proot -e'create database perl6test'
項目
データベース名 perl6test
ユーザ名 root
パスワード root

今回はこれを使います。

DBIish you a merry Christmas

接続
use v6;
use DBIish;

my
$dbh = DBIish.connect(
  "mysql",
  :database<perl6test>,
  :user<root>,
  :password<root>,
  :RaiseError
  );
テーブル作成
my
$sth = $dbh.do(q:to/STATEMENT/);
  DROP TABLE IF EXISTS idol ;
STATEMENT

$sth = $dbh.do(q:to/STATEMENT/);
  CREATE TABLE idol (
    id          SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    family_name VARCHAR(12),
    last_name   VARCHAR(12),
    age         TINYINT UNSIGNED
  ) ;
STATEMENT

プリペアドステートメント

$sth = $dbh.prepare(q:to/STATEMENT/);
    INSERT INTO idol (family_name, last_name, age)
    VALUES ( ?, ?, ? ) ;
STATEMENT

$sth.execute('星宮', 'いちご', 16);
$sth.execute('霧矢', 'あおい', 16);
$sth.execute('紫吹', '',    17);
$sth.execute('大空', 'あかり', 13);

fetchall_arrayref

my
$sth = $dbh.prepare(q:to/STATEMENT/);
    SELECT id, family_name, last_name, age FROM idol ;
STATEMENT

$sth.execute;

my
$arrayref = $sth.fetchall_arrayref();

# 要素数
$arrayref.elems.say; #=> 4

# $arrayref の中身を dump ...
$arrayref.perl.say; #=> $[["1", "星宮", "いちご", "16"], ["2", "霧矢", "あおい", "16"], ["3", "紫吹", "蘭", "17"], ["4", "大空", "あかり", "13"]]

# family_nameとlast_nameだけとりだし
for @( $arrayref ) -> $idol {
  @( $idol ).[1,2].join.say;
}

fetchrow-hash

my
$sth = $dbh.prepare(q:to/STATEMENT/);
    SELECT id, family_name, last_name, age FROM idol ;
STATEMENT

$sth.execute;

loop {
 my $hash = $sth.fetchrow-hash ;
 last unless $hash ;

 # $hash の中身を dump 
 $hash.perl.say;

 # family_nameとlast_nameだけとりだし
 $hash.{'family_name', 'last_name'}.join.say;
}

メソッドは他にもたくさん。

切断

$sth.finish;
$dbh.disconnect;
(おまけ)ドキュメント参照のコマンド
$ p6doc DBIish

$ p6doc DBDish::Role::ErrorHandling
$ p6doc DBDish::Role::Connection
$ p6doc DBDish::Role::StatementHandle

おわりです。

参考や注釈

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?