One of the most common things Perl is used for when it comes to raw data files is importing them into databases. To import into databases in Perl, you need a special module. This is normally the DBI module, and you’ll access it by putting a “use” line at the top of your script. This tells Perl that you want to access an external module for more functionality.
use DBI;
$dbh = DBI->connect("dbi:SQLite:dbname=TESTDB");
Put this just below your first set of comments, and then run
./show
If it shows you your help as normal, then you have both DBI and SQLite installed on your system.
If it gives you the error “Can’t locate DBI.pm in …”, you’ll need to install DBI and SQLite.
If it gives you the error “install_driver(SQLite) failed: Can't locate DBD/SQLite.pm in @INC…”, this means that you have DBI but you’ll need to install SQLite.
- Installing from CPAN
- Fortunately, Perl has an easy way to install modules. Unfortunately, it isn’t so easy if you aren’t the system administrator. If you aren’t the system administrator, you’ll need to ask your system administrator to install it for you. If you are, you can do it yourself.
- Using SQLite
- Go ahead and remove that “$dbh = …” line that we added for testing. Leave “use DBI;” there.
- Creating tables
- Now we know how to open the database. SQL databases require tables. We need to create one if it does not already exist. Let’s go ahead and just make a subroutine to do this.
- Inserting data
- Okay, we’ve opened the database and we’ve created the table. Now we need to insert data into the table. It is time to add functionality to our --import switch.
- The final script
- This is the end of this script. We’ll start from scratch on the next one, and display our data.