Perl 与MySQL交互示例代码
示例代码(一)示例代码(二)
[*]#!/bin/env perl
[*]
[*]use strict;
[*]use Getopt::Std;
[*]use DBI;
[*]
[*]my %options;
[*]
[*]getopts('u:p:d:h:help',\%options); //冒号代表其后需要跟一个参数
[*]
[*]if (scalar(keys %options) < 4) {
[*] printf "USAGE\n";
[*] printf "\t%s -u username -p password -d database -h hostname/ip\n","$0";
[*] exit 0;
[*]}
[*]
[*]my $username = $options{u} if defined $options{u};
[*]my $password = $options{p} if defined $options{p};
[*]my $database = $options{d} if defined $options{d};
[*]my $hostname = $options{h} if defined $options{h};
[*]
[*]my $dsn = "DBI:mysql:database=$database;host=$hostname;port=3306";
[*]my $dbh = DBI->connect($dsn,"$username","$password",{PrintError=>0,RaiseError=>1})
[*] or die "Can't connect to mysql" . DBI->errstr;
[*]
[*]my $table = qq/
[*] CREATE TABLE IF NOT EXISTS test (
[*] order_id int(5) not null auto_increment,
[*] name varchar(10) not null default '',
[*] email varchar(20) not null default '',
[*] PRIMARY KEY (order_id));
[*] /;
[*]
[*]my $sth = $dbh->prepare($table);
[*] $sth->execute();
[*]
[*]my $data = qq/
[*] INSERT INTO test VALUES
[*] (null,'henry','henry\@abc.com'),
[*] (null,'tom','tom\@abc.com'),
[*] (null,'teddy','teddy\@abc.com');
[*] /;
[*]
[*] $sth = $dbh->do($data);
[*] my $query = qq/SELECT * FROM test/;
[*]
[*] $sth = $dbh->prepare($query);
[*] $sth->execute();
[*]
[*]while (my @array = $sth->fetchrow_array()) {
[*] print join "\t",@array,"\n";
[*]}
页:
[1]