DBD::CSV(3) User Contributed Perl Documentation DBD::CSV(3)
NAME
DBD::CSV - DBI driver for CSV files
SYNOPSIS
use DBI;
$dbh = DBI->connect ("DBI:CSV:f_dir=/home/joe/csvdb") or
die "Cannot connect: $DBI::errstr";
$sth = $dbh->prepare ("CREATE TABLE a (id INTEGER, name CHAR(10))") or
die "Cannot prepare: " . $dbh->errstr ();
$sth->execute or die "Cannot execute: " . $sth->errstr ();
$sth->finish;
$dbh->disconnect;
# Read a CSV file with ";" as the separator, as exported by
# MS Excel. Note we need to escape the ";", otherwise it
# would be treated as an attribute separator.
$dbh = DBI->connect (qq{DBI:CSV:csv_sep_char=\;});
$sth = $dbh->prepare ("SELECT * FROM info");
# Same example, this time reading "info.csv" as a table:
$dbh = DBI->connect (qq{DBI:CSV:csv_sep_char=\;});
$dbh->{csv_tables}{info} = { file => "info.csv"};
$sth = $dbh->prepare ("SELECT * FROM info");
DESCRIPTION
The DBD::CSV module is yet another driver for the DBI (Database independent interface for Perl). This one is based on the SQL "engine"
SQL::Statement and the abstract DBI driver DBD::File and implements access to so-called CSV files (Comma separated values). Such files are
mostly used for exporting MS Access and MS Excel data.
See DBI(3) for details on DBI, SQL::Statement(3) for details on SQL::Statement and DBD::File(3) for details on the base class DBD::File.
Prerequisites
The only system dependent feature that DBD::File uses, is the "flock ()" function. Thus the module should run (in theory) on any system
with a working "flock ()", in particular on all Unix machines and on Windows NT. Under Windows 95 and MacOS the use of "flock ()" is
disabled, thus the module should still be usable,
Unlike other DBI drivers, you don't need an external SQL engine or a running server. All you need are the following Perl modules, available
from any CPAN mirror, for example
ftp://ftp.funet.fi/pub/languages/perl/CPAN/modules/by-module
DBI The DBI (Database independent interface for Perl), version 1.00 or a later release
DBD::File
This is the base class for DBD::CSV, and it is included in the DBI distribution. As DBD::CSV requires version 0.37 or newer for
DBD::File it effectively requires DBI version 1.609 or newer.
SQL::Statement
A simple SQL engine. This module defines all of the SQL syntax for DBD::CSV, new SQL support is added with each release so you should
look for updates to SQL::Statement regularly.
Text::CSV_XS
This module is used for writing rows to or reading rows from CSV files.
Installation
Installing this module (and the prerequisites from above) is quite simple. You just fetch the archive, extract it with
gzip -cd DBD-CSV-0.1000.tar.gz | tar xf -
(this is for Unix users, Windows users would prefer WinZip or something similar) and then enter the following:
cd DBD-CSV-0.1000
perl Makefile.PL
make
make test
If any tests fail, let me know. Otherwise go on with
make install
Note that you almost definitely need root or administrator permissions. If you don't have them, read the ExtUtils::MakeMaker man page for
details on installing in your own directories. ExtUtils::MakeMaker.
Supported SQL Syntax
All SQL processing for DBD::CSV is done by the SQL::Statement module. Features include joins, aliases, built-in and user-defined
functions, and more. See SQL::Statement::Syntax for a description of the SQL syntax supported in DBD::CSV.
Table names are case insensitive unless quoted.
Using DBD-CSV with DBI
For most things, DBD-CSV operates the same as any DBI driver. See DBI for detailed usage.
Creating a database handle
Creating a database handle usually implies connecting to a database server. Thus this command reads
use DBI;
my $dbh = DBI->connect ("DBI:CSV:f_dir=$dir");
The directory tells the driver where it should create or open tables (a.k.a. files). It defaults to the current directory, thus the
following are equivalent:
$dbh = DBI->connect ("DBI:CSV:");
$dbh = DBI->connect ("DBI:CSV:f_dir=.");
(I was told, that VMS requires
$dbh = DBI->connect ("DBI:CSV:f_dir=");
for whatever reasons.)
You may set other attributes in the DSN string, separated by semicolons.
Creating and dropping tables
You can create and drop tables with commands like the following:
$dbh->do ("CREATE TABLE $table (id INTEGER, name CHAR(64))");
$dbh->do ("DROP TABLE $table");
Note that currently only the column names will be stored and no other data. Thus all other information including column type (INTEGER or
CHAR(x), for example), column attributes (NOT NULL, PRIMARY KEY, ...) will silently be discarded. This may change in a later release.
A drop just removes the file without any warning.
See DBI(3) for more details.
Table names cannot be arbitrary, due to restrictions of the SQL syntax. I recommend that table names are valid SQL identifiers: The first
character is alphabetic, followed by an arbitrary number of alphanumeric characters. If you want to use other files, the file names must
start with '/', './' or '../' and they must not contain white space.
Inserting, fetching and modifying data
The following examples insert some data in a table and fetch it back: First all data in the string:
$dbh->do ("INSERT INTO $table VALUES (1, ".
$dbh->quote ("foobar") . ")");
Note the use of the quote method for escaping the word 'foobar'. Any string must be escaped, even if it doesn't contain binary data.
Next an example using parameters:
$dbh->do ("INSERT INTO $table VALUES (?, ?)", undef, 2,
"It's a string!");
Note that you don't need to use the quote method here, this is done automatically for you. This version is particularly well designed for
loops. Whenever performance is an issue, I recommend using this method.
You might wonder about the "undef". Don't wonder, just take it as it is. :-) It's an attribute argument that I have never ever used and
will be parsed to the prepare method as a second argument.
To retrieve data, you can use the following:
my $query = "SELECT * FROM $table WHERE id > 1 ORDER BY id";
my $sth = $dbh->prepare ($query);
$sth->execute ();
while (my $row = $sth->fetchrow_hashref) {
print "Found result row: id = ", $row->{id},
", name = ", $row->{name};
}
$sth->finish ();
Again, column binding works: The same example again.
my $sth = $dbh->prepare (qq;
SELECT * FROM $table WHERE id > 1 ORDER BY id;
;);
$sth->execute;
my ($id, $name);
$sth->bind_columns (undef, $id, $name);
while ($sth->fetch) {
print "Found result row: id = $id, name = $name
";
}
$sth->finish;
Of course you can even use input parameters. Here's the same example for the third time:
my $sth = $dbh->prepare ("SELECT * FROM $table WHERE id = ?");
$sth->bind_columns (undef, $id, $name);
for (my $i = 1; $i <= 2; $i++) {
$sth->execute ($id);
if ($sth->fetch) {
print "Found result row: id = $id, name = $name
";
}
$sth->finish;
}
See DBI(3) for details on these methods. See SQL::Statement(3) for details on the WHERE clause.
Data rows are modified with the UPDATE statement:
$dbh->do ("UPDATE $table SET id = 3 WHERE id = 1");
Likewise you use the DELETE statement for removing rows:
$dbh->do ("DELETE FROM $table WHERE id > 1");
Error handling
In the above examples we have never cared about return codes. Of course, this cannot be recommended. Instead we should have written (for
example):
my $sth = $dbh->prepare ("SELECT * FROM $table WHERE id = ?") or
die "prepare: " . $dbh->errstr ();
$sth->bind_columns (undef, $id, $name) or
die "bind_columns: " . $dbh->errstr ();
for (my $i = 1; $i <= 2; $i++) {
$sth->execute ($id) or
die "execute: " . $dbh->errstr ();
$sth->fetch and
print "Found result row: id = $id, name = $name
";
}
$sth->finish ($id) or die "finish: " . $dbh->errstr ();
Obviously this is tedious. Fortunately we have DBI's RaiseError attribute:
$dbh->{RaiseError} = 1;
$@ = "";
eval {
my $sth = $dbh->prepare ("SELECT * FROM $table WHERE id = ?");
$sth->bind_columns (undef, $id, $name);
for (my $i = 1; $i <= 2; $i++) {
$sth->execute ($id);
$sth->fetch and
print "Found result row: id = $id, name = $name
";
}
$sth->finish ($id);
};
$@ and die "SQL database error: $@";
This is not only shorter, it even works when using DBI methods within subroutines.
DBI database handle attributes
Metadata
The following attributes are handled by DBI itself and not by DBD::File, thus they all work as expected:
Active
ActiveKids
CachedKids
CompatMode (Not used)
InactiveDestroy
Kids
PrintError
RaiseError
Warn (Not used)
The following DBI attributes are handled by DBD::File:
AutoCommit
Always on
ChopBlanks
Works
NUM_OF_FIELDS
Valid after "$sth->execute"
NUM_OF_PARAMS
Valid after "$sth->prepare"
NAME
NAME_lc
NAME_uc
Valid after "$sth->execute"; undef for Non-Select statements.
NULLABLE
Not really working. Always returns an array ref of one's, as DBD::CSV doesn't verify input data. Valid after "$sth->execute"; undef for
non-Select statements.
These attributes and methods are not supported:
bind_param_inout
CursorName
LongReadLen
LongTruncOk
DBD-CSV specific database handle attributes
In addition to the DBI attributes, you can use the following dbh attributes:
f_dir
This attribute is used for setting the directory where CSV files are opened. Usually you set it in the dbh, it defaults to the current
directory ("."). However, it is overwritable in the statement handles.
f_ext
This attribute is used for setting the file extension.
f_schema
This attribute allows you to set the database schema name. The default is to use the owner of "f_dir". "undef" is allowed, but not in
the DSN part.
my $dbh = DBI->connect ("dbi:CSV:", "", "", {
f_schema => undef,
f_dir => "data",
f_ext => ".csv/r",
}) or die $DBI::errstr;
csv_eol
csv_sep_char
csv_quote_char
csv_escape_char
csv_class
csv_csv
The attributes csv_eol, csv_sep_char, csv_quote_char and csv_escape_char are corresponding to the respective attributes of the
Text::CSV_XS object. You want to set these attributes if you have unusual CSV files like /etc/passwd or MS Excel generated CSV files
with a semicolon as separator. Defaults are "