We Recommend

Learning Perl Learning Perl
In this smooth, carefully paced course, a leading Perl trainer teaches you to program in the language that threatens to make C, sed, awk, and the Unix shell obsolete for many tasks. This book is the "official" guide for both formal (classroom) and informal learning. It is fully accessible to the novice programmer.


Posted By

eszpee on 02/14/08


Tagged

mysql select sql insert


Versions (?)


MySQL based functions


Published in: Perl 


  1. sub db_connect {
  2. my ($dbname, $dbuser, $dbpass) = @_;
  3. my $dbh = DBI->connect("DBI:mysql:$dbname",$dbuser,$dbpass);
  4. #$dbh->do(qq{set character set 'utf8';});
  5. return $dbh;
  6. }
  7.  
  8. sub do_sql {
  9. # Takes: $dbh, $sql
  10. # Returns: status
  11. my $dbh = shift || die "Database not connected!\n";
  12. my $sql = shift || die "Missing SQL statement???\n";
  13. return $dbh->do($sql);
  14. }
  15.  
  16. sub execute_sql {
  17. # Takes: $dbh, $sql
  18. # Returns: $result_arrayref
  19. my $dbh = shift || die "Database not connected!\n";
  20. my $sql = shift || die "Missing SQL statement???\n";
  21. my $sth = $dbh->prepare($sql);
  22. $sth->execute;
  23. my $result = $sth->fetchall_arrayref({}); # {} => Return arrayref of hashrefs
  24. return $result;
  25. }
  26.  
  27. sub do_insert {
  28. #takes: $dbh, $table, $datahash
  29. #returns: status
  30. my $dbh = shift || die "Database not connected!\n";
  31. my $table = shift || die "Missing table!\n";
  32. my $datahash = shift || die "Nothing to insert!\n";
  33. my $insert = "INSERT INTO $table (" . join(',', keys %$datahash) . ') VALUES (' . join(',', values %$datahash) . ');';
  34. return &do_sql($dbh, $insert);
  35. }

Report this snippet 

You need to login to post a comment.