Chinaunix首页 | 论坛 | 博客
  • 博客访问: 111719
  • 博文数量: 25
  • 博客积分: 1094
  • 博客等级: 少尉
  • 技术积分: 284
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-25 16:36
文章分类

全部博文(25)

文章存档

2011年(14)

2010年(11)

分类: Python/Ruby

2011-05-25 09:40:57

  1. #!/usr/bin/perl -w
  2. use strict;
  3. use DBI;
  4. use Data::Dumper;


  5. my $this_dbh = &MysqlConnect( $MyDB, $MyHost, $MyUser, $MyPass );
  6. $this_dbh->do("SET NAMES 'utf8'");

  7. my $ExecGroup = &ExecuteSQL( $this_dbh, "SELECT gname FROM groups;");

  8. sub MysqlConnect {
  9.      my ( $sqlName, $host, $user, $pass ) = @_;
  10.      return DBI->connect( "DBI:mysql:database=$sqlName;host=$host", "$user", "$pass", { 'RaiseError' => 1 } );
  11.         }
  12.     #########################
  13.     #执行SQL语句,返回hash
  14.     #########################
  15. sub ExecuteSQL($$@){
  16.       my ($tmpdbh,$tmpsql,@param)=@_;
  17.       my $qpcount = grep {/\?/} (split //,$tmpsql); #count the parameter number
  18.             die "Your query parameter does not match the SQL!" if ($qpcount != scalar(@param));
  19.             #replace the ? with the input parameter
  20.             foreach my $ele(@param){
  21.                     $_=$tmpsql;
  22.                     s/\?/$ele/;
  23.                     $tmpsql=$_;
  24.             }
  25.             #print "Execute SQL : $tmpsql\n";
  26.             #########################################################
  27.             #only for debug info,Func will return for update statment
  28.             #########################################################
  29.             #return undef unless($tmpsql =~ /^select/);
  30.             my %tmphash; #store the query result
  31.             ##connect DB and execute the SQL
  32.             my $sth=$tmpdbh->prepare($tmpsql);
  33.             return undef unless($sth->execute);
  34.             my $count=1; #this is count the returned row and used as the key for hash result
  35.             #save the query result to the hash
  36.             while(my $row=$sth->fetchrow_hashref){
  37.                     my %innerhash;
  38.                     @innerhash{keys%{$row}}=values%{$row};
  39.                     $tmphash{"$count"}=\%innerhash;
  40.                     $count++;
  41.             }
  42.             $sth->finish();
  43.             return \%tmphash;
  44.     }
阅读(1604) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~