yanglgzh 发表于 2018-9-1 07:31:25

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 &quot;USAGE\n&quot;;
[*]      printf &quot;\t%s -u username -p password -d database -h hostname/ip\n&quot;,&quot;$0&quot;;
[*]      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 = &quot;DBI:mysql:database=$database;host=$hostname;port=3306&quot;;
[*]my $dbh = DBI->connect($dsn,&quot;$username&quot;,&quot;$password&quot;,{PrintError=>0,RaiseError=>1})
[*]               or die &quot;Can't connect to mysql&quot; . 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 &quot;\t&quot;,@array,&quot;\n&quot;;
[*]}
  



页: [1]
查看完整版本: Perl 与MySQL交互示例代码