in reply to perl create database with folder system
I liked NetWallah's post at Re: perl create database with folder system.
I wrote some Perl code for you below. Run it, play with it. Experimentation is definitely encouraged!
In creating the table, Animal, I let the DB assign a unique ID for each "row" (see code). This is normally a good idea- so good that you should explain why you don't want that. This idea guarantees and unique id for each row even with multiple simultaneous writers. There are some "do" statements, but the normal way using the Perl DBI is to "prepare" an SQL statement and then later execute it with some variables. There are a number of ways to get the results of "execute". I show one of those ways.
The Perl DBI comes standard in many (if not all) distributions. I don't think that you will have to install anything to run the code below. I used to use a Firefox SQLite add-on as a UI but I am hearing that this is no longer supported. Bummer.
Anyway, this code "runs":
Update:#!/usr/bin/perl use strict; use warnings; use DBI; my $dbfile = 'TestDB.sqlite'; #whatever SQLite DB name you want # SQLite doesn't have a user name or password, but needs a # "connection" my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","",{RaiseError = +> 1}) or die "Couldn't connect to database: " . DBI->errstr; # I put in this DROP so that you can run this code again # and again while you play with it. $dbh->do("DROP TABLE IF EXISTS Animal"); $dbh->do("CREATE TABLE Animal ( id integer PRIMARY KEY AUTOINCREMENT, Type varchar(10), Name varchar(10) ); "); my $add_animal = $dbh->prepare ("INSERT INTO Animal (Type,Name) VALUES (?,?)"); ## Make a single "transaction" for all inserts ## This is a huge performance increase if making thousands of inserts ## A DB INSERT is "expensive" due to the booking involved ## A million inserts can be part of a single transaction $dbh->do("BEGIN"); # start a new transaction for all inserts while (defined (my $line = <DATA>)) { chomp $line; my ($type,$name) = split /\|/, $line; $add_animal->execute($type,$name); } $dbh->do("COMMIT"); #massive speed up by making one transaction!! ## An Example of Query by Type my $query_by_type = $dbh->prepare ("SELECT * FROM Animal WHERE Type IS ?"); $query_by_type->execute('lion'); my $table_ref = $query_by_type->fetchall_arrayref; foreach my $row (@$table_ref) { print "@$row\n"; } =Prints: 4 lion Simba 5 lion Elsa =cut __DATA__ cat|Felix cat|Sylvester cat|Garfield lion|Simba lion|Elsa tiger|Sher Khan dog|Rover
|
|---|