天天看點

Perl 與MySQL互動示例代碼

示例代碼(一)

<a href="http://blog.51cto.com/attachment/201101/124414179.png" target="_blank"></a>

示例代碼(二)

#!/bin/env perl 

use strict; 

use Getopt::Std; 

use DBI; 

my %options; 

getopts('u:p:d:h:help',\%options); //冒号代表其後需要跟一個參數

if (scalar(keys %options) &lt; 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-&gt;connect($dsn,"$username","$password",{PrintError=&gt;0,RaiseError=&gt;1}) 

               or die "Can't connect to mysql" . DBI-&gt;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-&gt;prepare($table); 

   $sth-&gt;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-&gt;do($data); 

    my $query = qq/SELECT * FROM test/; 

   $sth = $dbh-&gt;prepare($query); 

while (my @array = $sth-&gt;fetchrow_array()) { 

       print join "\t",@array,"\n"; 

 本文轉自dongfang_09859 51CTO部落格,原文連結:http://blog.51cto.com/hellosa/487010,如需轉載請自行聯系原作者