Tk::DBI::DBGrid - grid for browse and edit database.
use DBI;
use Tk;
use Tk::DBI::DBGrid;
my $dbh = DBI->connect( $dbhstr, $name, $pas, {AutoCommit => 0, RaiseError => 0}) or die DBI::errstr;
my $w = $MW->Toplevel(-title => 'dbgrid');
.....
my $sql = "SELECT field0, field1, field2 FROM table0";
# read only
my $grid = $w->DBGrid( -dbh => $dbh, -sql => $sql )->pack;
# with edit, without INSERT and DELETE
my @pkey = ('field0');
my $upd = sub {
my @row = @_;
..... # any kod before UPDATE, if need
$dbh->do("UPDATE table0 SET WHERE field0 = $row[0]");
$dbh->commit;
..... # any kod after UPDATE, if need
0; # zero is nnecessary for future
};
my $grid = $w->DBGrid( -dbh => $dbh, -sql => $sql, -maxrow => 10, -edit => 1,
-pkey => \@pkey, -updfunc => $upd, -font => 'Courier 10' )->pack;
# with INSERT, DELETE and formating sells
my @pkey = ('field0');
my @cell;
$cell[0]{width} = 5;
$cell[0]{edit} = 0; # primary key need read only
$cell[0]{name} = 'title0' # new title for field0
$cell[1]{width} = undef; # width field read from table
$cell[1]{edit} = 1;
$cell[2]{width} = 7;
$cell[2]{edit} = 1;
$cell[2]{justify} = 'left';
my $ins = sub {
my @row = @_;
......
$dbh->do("INSERT INTO table0 (field0, field1, field2) VALUES ($row[0], $row[1], $row[2])");
$dbh->commit;
......
0;
};
my $upd = sub {
my @row = @_;
.....
$dbh->do("UPDATE table0 SET WHERE field0 = $row[0]");
$dbh->commit;
.....
0;
};
my $del = sub {
my ($pkey) = @_;
.....
$dbh->do("DELETE FROM table0 WHERE field0 = $pkey");
$dbh->commit;
.....
0;
};
my %fkey;
$fkey{ins} = 'Key-F5';
$fkey{del} = 'Key-F8';
my $grid = $w->DBGrid( -dbh => $dbh, -sql => $sql, -maxrow => 10, -edit => 1,
-pkey => \@pkey, -insfunc => $ins, -updfunc => $upd, -delfunc => $del,
-font => 'Courier 10', -cellformat =>\@cell, -fkeys => \%fkey )->pack(-fill => 'x');
DBGrid allows to browse/edit any table to which a query can be applied. The query may join several tables.
Every record should be monosemantically defined by some field perfoming a primary key function for editing. So as to transfer changes to the database one may use the functions, pointers to which have been delivered to the constructor ( -insfunc, -updfunc & -delfunc ). The functions themselves are described in the basic program text. If a pointer is not for delivering or undef is transferred the action is not worked up. If the key words of group operation or UNION are found in the query, DBGrid will turn to browse mode ( -edit => 0 ). The data are not refreshed after calling functions in this DBGrid version.
Table parameters define every field parameter of reflection (the length and type - char, numeric or others - are read). Editing for the field defined through -pkey is inaccessible. All DBGrid cells are the control elements Label or Entry and after visibility one may rule them separately, for example $grig->{rowframee}->[$i][$j]->configure( -font => 'Courier 12').
Vadim Likhota vadim-lvv[at]yandex.ru
dbgrid, entry, label, database, table