[Perl] script -database


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting [Perl] script -database
# 1  
Old 01-18-2011
[Perl] script -database

Welcome. I am writing a perl script. I have to design a database consisting of a single table (any subject) saved in a text file. (I make it vi command name and I am giving permission chmod u + x?) The table should contain at least four columns, including a column containing the ID (serial number ) and at least one column of text and numerical data. application written in Perl should allow:
-sort the selected column.
- adding new rows (lines) to the database - with the auto increment Serial Number (ID)
-printing lines with possibility of search in any column (using the regular expression specified by the user), the print order of tuples consistent with the natural order in the file

PLEASE guidance, which in turn have to do. Can someone please bring me a little bit, how do the jobSmilie I hope my English is understandableSmilie Smilie

Smilie
# 2  
Old 01-19-2011
SQLite

Most of database stuff is done for you already with SQLite and there's a CPAN.org module for it. See module DBD::SQLite. Other methods can be found on the link to DBD from the module. On Linux use your package manager to install it, search for "dbd-sqlite". Windows can install it with PPM but I haven't used that in some time.

I also have packages "sqlite" (command line), "sqlite-doc" (docs) and "sqliteman" (GUI) installed under Linux. This is everything you need to create the database file without PERL. You can learn the syntax and play around with the DB. DB File needs RW access and the directory must be at least X (executable).

PERL access starts with...

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

my $dbh = DBI->connect("dbi:SQLite:$dbfile","","");
my $sth = $dbh->prepare("SELECT * FROM users ORDER BY id");
$sth->execute or die $sth->errstr;
my $row = $sth->fetch;
while (defined($row)) {
    print join("|", @$row), "\n";
    $row = $sth->fetch;
}

$dbh->disconnect;

There are lots of ways to get rows, see all the fetch methods in the DBD module. For example, you can get one row at a time in an array or in a hash, or all the rows at once in an array or array ref, etc. Variables can be bound to columns for easier access.

The table was created from command line. Here's the SQL92 statement.

Code:
CREATE TABLE users (id integer primary key, fname varchar(40), lname varchar(40));

SQL92 is a subset of the full standard, see documentation.

Last edited by m1xram; 01-28-2011 at 10:28 AM.. Reason: missing semicolon
# 3  
Old 01-21-2011
Thank you. But it says much to me. Could someone help me write this script?
# 4  
Old 01-27-2011
design

Thought about it for a long time as this could be a lengthy procedure and I'm a bit busy with my job now. But I can help you in my spare time.

To create your simple database we need to know what's inside it. I can pick column names but if you have something more specific in mind let me know. How about basic inventory?

Columns: Number, Name, Spec, Notes
  1. id, int primary key, Will auto increment with null value.
  2. qty, int8
  3. price, int8, Value is cents or 1=1/100 of dollar.
  4. item, varchar(20), Item name.
  5. desc, varchar(255), Text description.
Sound good? Will post SQL for sqlite and PERL to create DB and insert rows when I have more time. Sorry for delay.

Last edited by m1xram; 01-28-2011 at 01:14 AM.. Reason: fix columns def
# 5  
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);
}

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. 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

2. 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

3. 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

4. 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

5. 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

6. 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

7. 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

8. 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

9. 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

10. 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
Login or Register to Ask a Question