About Me

Friday, 20 April 2012

PERL - Select Database

PERL - Select Database

In order to perform even the simplest of queries we must first select a database to be working with. Since we have our database name already listed with our config variables, things will be quite simple.

perlmysqlselectdb.pl:

#!/usr/bin/perl

# PERL MODULE
use Mysql;

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);
Notice how the syntax requires that we connect to our host each time we perform a function. You will see this with nearly every script we execute. Once we are connected, the sky is the limit as to what queries we can execute.

PERL - List Tables Function

A function exists to list the tables in a database just like the listdbs() function. Use the listtables() function to list each table in a database.

listtables.pl:

#!/usr/bin/perl

use Mysql;

# HTTP HEADER
print "Content-type: text/html \n\n";

# MYSQL CONFIG VARIABLES
$host = "localhost";
$database = "store";
$tablename = "inventory";
$user = "username";
$pw = "password";

# PERL MYSQL CONNECT()
$connect = Mysql->connect($host, $database, $user, $pw);

# SELECT DB
$connect->selectdb($database);

# LISTTABLES()
@tables = $db->listtables;

# PRINT EACH TABLE NAME
@tables = $connect->listtables;
foreach $table (@tables) {
 print "$table<br />";
}
The database is defined when we run the $connect variable. To change the script to a different database simply run a new selectdb() function or change the $database variable.

0 comments:

Post a Comment