Sponsored Content
Full Discussion: [Perl] script -database
Top Forums Shell Programming and Scripting [Perl] script -database Post 302492283 by m1xram on Sunday 30th of January 2011 10:37:25 PM
Old 01-30-2011
Commands Report and Add for DB

Here's an Sqlite dump of the table def:
Code:
CREATE TABLE parts (id integer primary key autoincrement,qty int8 not null,price int8 not null,item varchar(20) not null unique,desc varchar(255) not null);

Here's some PERL code to add items or show a report of the table. No options are implemented.
Code:
#!/usr/bin/perl -w

use DBI qw(:sql_types);
my $dbfile = "parts_inventory.sqlite";

sub cmd_add {
    print "add:\n";
    my %record;
    foreach my $f ("item", "desc", "qty", "price") {
        my $aarg = shift(@ARGV);
        if ((! defined($aarg)) || ($aarg eq ":")) {
            # Error: some data is missing.
            printf("%%Error - Add command missing \"%s\".\n", $f);
            exit(1);
        } elsif ($aarg =~ /^-/) {
            # Option
        } else {
            # Data
            $record{$f} = $aarg;
        }
    }
    my $dbh = DBI->connect("dbi:SQLite:$dbfile","","");
    my $cmdh = $dbh->prepare("insert into parts " .
                             "values(null, ?, ?, ?, ?);");
    $cmdh->execute($record{"qty"}, $record{"price"} * 100, $record{"item"}, 
                   $record{"desc"}, ) or die "%Error - " . $cmdh->errstr();
    $dbh->disconnect();
    
}

sub cmd_report {
    print "report:\n";
    dbreport_by_id($dbfile);
}

sub dbcreate($) {
    printf("%%Warning - DBfile \"%s\" missing, creating new file.\n",
          $dbfile);
    # Touch file.
    my $now = time;
    utime($now, $now, $dbfile);

    my $dbh = DBI->connect("dbi:SQLite:$dbfile","","");
    my $cmdh = $dbh->prepare("create table parts (" .
                             "id integer primary key autoincrement," .
                             "qty int8 not null," .
                             "price int8 not null," .
                             "item varchar(20) not null unique," .
                             "desc varchar(255) not null);");
    $cmdh->execute() or die "%Error - " . $cmdh->errstr();
    $dbh->disconnect();
}

sub dbreport_by_id($) {
    my $dbh = DBI->connect("dbi:SQLite:$dbfile","","");
    my $sth = $dbh->prepare("SELECT * FROM parts ORDER BY id;");
    $sth->execute() or die "%Error - " . $sth->errstr();
    while (my $row = $sth->fetch()) {
        $row->[2] /= 100;
        print join("|", @$row), "\n";
    }
    $dbh->disconnect();
}

sub usage ($) {
    my $l = length("Usage - $0");

    print "\nUsage - $0 " . '[ SUBCMD [OPTIONS] DATA ... ] ' .
        '[ [ ":" SUBCMD [OPTIONS] DATA ... ] ... ]' . "\n";
    my $fmt = sprintf("%%%ds %%s\n", $l);
    printf($fmt, " ", "SUBCMD: report R_OPTIONS");
    printf($fmt, " ", "SUBCMD: add A_OPTIONS");
    print "\n";
    exit($_[0]);
}
if (! -e $dbfile) {
    dbcreate($dbfile);
}

# thiscmd [ subcmd [options] data ... ] [ ":" subcmd [options] data ... ] ...
# subcmd = report_cmd | add_cmd
# report_cmd = "report" report_opt [ report_opt ... ]
# report_opt = ( "-ascend" colname ) | ( "-desend" colname ) | 
#    ( "-limit" number )
# colname = "item" | "desc" | "qty" | "price"

# add_cmd = "add" add_data
# add_data = item_name description qty price

my $myprog = $0;
my $arg = shift(@ARGV);
my %cmds = ("add" => \&cmd_add, "report" => \&cmd_report, 
    "help" => \&usage);
if (! defined($arg)) {
    usage(0);
}

while ($arg) {
    # use hash for function call
    if ($arg ne ":") {
        if (exists($cmds{$arg})) {
            # Call subref
            &{$cmds{$arg}}
        } else {
            usage(1);
        }
    }
    $arg = shift(@ARGV);
}

 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

error connecting database from perl

Hi, While i am trying to connect to Oracle database from Perl using DBI module,am getting the error as follows : Can't load '/usr/local/fuseperl-modules/lib/i586-linux-thread-multi/auto/DBD/Oracle/Oracle.so' for module DBD::Oracle: libwtc9.so: cannot open shared object file: No such file... (4 Replies)
Discussion started by: DILEEP410
4 Replies

2. Shell Programming and Scripting

Perl Database access

Hi, I tried to run this code but it isnt giving me any output or errors. My aim is to retrieve the row based on the flag name(this is the primary key). flag_test is my table This is how i ran it: perl read_db.pl flag1 flag1 is the criteria in where clause -------- this is my... (2 Replies)
Discussion started by: mercuryshipzz
2 Replies

3. Shell Programming and Scripting

Automating A Perl Script over a database

Dear Scripting Gods I've never done shell scripting before and have only recently got to grips with Perl, so apologies for my naivity. I've written a perl program which takes in two files as arguments (these are text documents which take in the information I need) The perl program spits out a... (1 Reply)
Discussion started by: fraizerangus
1 Replies

4. Shell Programming and Scripting

perl, testing a database for a match

hi there. in perl, I am struggling to find a simple method of connecting to a database, determining if the result of my query is "true" and then testing against the result. I dont even really want the data that i am 'SELECT'íng. i effectively just want to check that a record exists with a UID... (2 Replies)
Discussion started by: rethink
2 Replies

5. Shell Programming and Scripting

Perl script to connect to database using JDBC driver?

How to connect to SQL Server database from perl script using JDBC driver? ---------- Post updated at 05:33 PM ---------- Previous update was at 05:07 PM ---------- i have sqljdbc.jar file. by setting the class path how can i connect to the database using perl script? (2 Replies)
Discussion started by: laknar
2 Replies

6. Shell Programming and Scripting

help with perl database printing

Hey guys i am using perl and trying to pull a list of books from a database and then populate the list in a separate TT2 file. When the list is generated there should be 39 book names. When I do the foreach statement in my tt2 below, the first statement gives me 39 Array(random number) and the... (1 Reply)
Discussion started by: Joey12
1 Replies

7. Programming

Help with mySQL database by perl script

Hello; I was trying to set up a mysql database using following script, but never went through. The code seems fine without any syntax error as I tested it: perl -c Brapa0101-db.pl Brapa0101-db.pl syntax OKHowever, whenever I run it, an error message was tossed out: DBD::mysql::st execute... (7 Replies)
Discussion started by: yifangt
7 Replies

8. UNIX and Linux Applications

SQL database call into Multidimensional Array using Perl Script

#!/usr/local/bin/perl use DBI; use File::Copy; use Time::Local; use Data::Dumper; -Comments Describing what I'm doing-------------- -I'm pulling information from a database that has an ID and Name. They are separated by a space and I'm trying to load them into a multidimensional array so as... (3 Replies)
Discussion started by: eazyeddie22
3 Replies

9. Shell Programming and Scripting

Perl script database date convertion

Need assistance Below script get the output correctly I want to convert the date format .Below is the output . Any idea ? #!/usr/bin/perl -w use DBI; # Get a database handle by connecting to the database my $db = DBI->connect(... (3 Replies)
Discussion started by: ajayram_arya
3 Replies

10. Shell Programming and Scripting

Help required for Oracle database shutdown script conversion from shell to perl

Please tell me how to convert below program from shell script to perl. Same commands need to use in shutdown, just need program help for startup. export ORACLE_BASE=/home/oracle1 lsnrctl start lndb1 sqlplus '/ as sysdba' startup; (2 Replies)
Discussion started by: learnbash
2 Replies
All times are GMT -4. The time now is 10:39 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy