広告
広告
https://www.7key.jp/mysql_perl2.html#a_01以下の解説は、Perl、MySQLのインストールはもちろんのこと、DBI 等インターフェイスのインストールも完了していることが前提です。 詳細につきましては「MySQL をインストールし、Perl から接続できるように設定する」を参照ください。
https://www.7key.jp/mysql_perl2.html#a_02#!/usr/bin/perl
use DBI;
$ds = 'DBI:mysql:enet;host=localhost;port=/tmp/mysql.sock';
$user = 'user';
$pass = 'user';
$db = DBI->connect($ds, $user, $pass) || die "Got error $DBI::errstr when connecting to $ds\n";
$sth = $db->prepare("SELECT * FROM table_name WHERE column_1 LIKE \'\%$string\%\'");
$sth->execute;
print "Content-type: text/html;\n\n";
while(@row = $sth->fetchrow_array) {
print "@row<br>\n";
}
$rc = $sth->finish;
$rc = $db->disconnect;
exit;
https://www.7key.jp/mysql_perl2.html#a_03「"SELECT seq, name, tel, add FROM table_name"」のように特定のカラムからクエリを作成することも可能。SQL同様、ワイルドカードは「%」(パーセント)を使用します。
https://www.7key.jp/mysql_perl2.html#a_04#!/usr/bin/perl
use DBI;
$ds = 'DBI:mysql:enet;host=localhost;port=/tmp/mysql.sock';
$user = 'user';
$pass = 'user';
$db = DBI->connect($ds, $user, $pass) || die "Got error $DBI::errstr when connecting to $ds\n";
$sth = $db->prepare("INSERT INTO table_name VALUES (99,\'piyo\',\'hoge\',\'$string\')");
$sth->execute;
$rc = $sth->finish;
$rc = $db->disconnect;
exit;
https://www.7key.jp/mysql_perl2.html#a_05上記のように全カラムが対象の場合は、カラム名を省略してレコードを挿入することができます。このとき「VALUES」にて指定した値が、カラム数に足りなかったり多かったりした場合はエラーとなります。また、データ挿入するカラム型によっては「’」(シングルクォート)にて囲まなければなりません(Char、Textなど)。カラムを指定してレコードを挿入する場合はINSERT INTO table_name (seq, name, tel, add) VALUES (99,\'piyo\',\'hoge\',\'$string\')のようなSQL文を発行します。
https://www.7key.jp/mysql_perl2.html#a_06#!/usr/bin/perl
use DBI;
$ds = 'DBI:mysql:enet;host=localhost;port=/tmp/mysql.sock';
$user = 'user';
$pass = 'user';
$db = DBI->connect($ds, $user, $pass) || die "Got error $DBI::errstr when connecting to $ds\n";
$sth = $db->prepare("UPDATE table_name SET colmn_name=\'新規値\' WHERE seq = \'99\'");
$sth->execute;
$rc = $sth->finish;
$rc = $db->disconnect;
exit;
https://www.7key.jp/mysql_perl2.html#a_07#!/usr/bin/perl
use DBI;
$ds = 'DBI:mysql:enet;host=localhost;port=/tmp/mysql.sock';
$user = 'user';
$pass = 'user';
$db = DBI->connect($ds, $user, $pass) || die "Got error $DBI::errstr when connecting to $ds\n";
$sth = $db->prepare("DELETE FROM table_name WHERE seq = \'99\'");
$sth->execute;
$rc = $sth->finish;
$rc = $db->disconnect;
exit;
https://www.7key.jp/mysql_perl2.html#a_08#!/usr/bin/perl
use DBI;
$ds = 'DBI:mysql:enet;host=localhost;port=/tmp/mysql.sock';
$user = 'user';
$pass = 'user';
$db = DBI->connect($ds, $user, $pass) || die "Got error $DBI::errstr when connecting to $ds\n";
$sth = $db->prepare("SELECT * FROM table_name WHERE $where ORDER BY seq DESC");
$sth->execute;
$rc = $sth->finish;
$rc = $db->disconnect;
exit;
https://www.7key.jp/mysql_perl2.html#a_09昇順に並び替える場合は「ORDER BY カラム名」、昇順に並び替える場合は「ORDER BY カラム名 DESC」
広告