read_write_db.pm v0.3.7
eng:
add some useful comment.
cn:
加入些有用的注释。
#!/usr/bin/perl
# file:read_write_db.pm
# read mysql database into hashref or write back hashref to database.
# by:1e0n 05/10/27 v0.3.7
package read_write_db;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(read_db write_db);
use DBI();
use read_conf qw($user $pwd);
sub read_db {
# Use Typeglob to make a efficient prarmeter passing
local (*cp_prime_n_array,*cp_prime_step_id) = @_;
my $n;
# Connect to the database.
my $dbh = DBI->connect("DBI:mysql:database=prime_db;host=localhost",
$user,$pwd,
{’RaiseError’ => 1});
# pick out all prime to ref && sqrt_of_prime_id to ref
# that’s a little slowly process if we have a big database
my $prime_n_ref = $dbh->selectall_arrayref("SELECT prime_n FROM prime_table");
my $prime_step_id_ref = $dbh->selectrow_arrayref("SELECT MAX(prime_step_id) FROM prime_table");
# copy prime to array "copy_prime",$cp_prime_n_array[0] is no use but we let it equal 1.
# we start from $cp_prime_n_array[1] = 2 which mean the first prime is 2.
# that’s really not a good method to change data type but no matter,it’s fast enough.
@cp_prime_n_array = (1);
foreach (@$prime_n_ref) {
$cp_prime_n_array[++$n]=$_->[0];
}
$cp_prime_step_id = $prime_step_id_ref->[0];
#列数: $#{$ref}+1 行数?: $#{$ref->[0]}+1 提取一个数:@$ref[0]->[1];
# after reading data disconnect mysql
$dbh -> disconnect();
}
sub write_db {
local (*cp_new_prime_id_array,*cp_new_prime_n_array,*cp_prime_step_id)=@_;
# Connect to the database.
my $dbh = DBI->connect("DBI:mysql:database=prime_db;host=localhost",
$user,$pwd,
{’RaiseError’ => 1});
$insert = $dbh->prepare("INSERT INTO prime_table (id,prime_n,prime_step_id) VALUES (?,?,?)");
my $i=0;
for (@cp_new_prime_id_array) {
$insert->execute($_,$cp_new_prime_n_array[$i],$cp_prime_step_id) or die ($dbh->errstr);
$i++;
}
# after reading data clear memory && disconnect mysql
$insert->finish();
$dbh -> disconnect();
}
1;