Create Table
2002-05-02 14:32:28
Category: perl:database
Description: Example of creating and dropping tables as well as adding, deleteing, and updating rows of a sql database from perl.
Author: Snap
Viewed: 3958
Rating: (12 votes)


#!/usr/bin/perl
print "Content text:html/text\n\n";
use DBI;
 
#####################################
#                                   #
# Written by Snap                   #
#      (iam@someoneshouse.com)      #
#   for MetalShell                  #
#      (http://wwww.metalshell.com) #
# NOTE:  This program is just for   #
# example purposes.  To see what it #
# actually does you need to comment #
# out or edit sections.             #
#                                   #
#####################################
 
###Replace user and password with your username and password
$user = "metalshell";
$pass = "pass";
###Replace dbname with the name of your database
$dab = "dbname";
 
$dbh = DBI->connect("DBI:mysql:$dab",$user,$pass);
 
###Creates the Table we'll be working with
$CreateTable=$dbh->prepare(
"create table mytable(ID varchar(30) NOT NULL,
Name varchar(30) NOT NULL)"
);
 
$CreateTable->execute();
my @info=();
 
print "Table Created\n\n";
 
###Variation on the way you can work with sql in perl
###Inserting a value into the newly created table
$InsertValue="insert into mytable values(5,'Snap')";
$rtn=$dbh->do($InsertValue);
 
print "User Added\n\n";
 
#Create value for next transaction
$user="detour";
 
###Now Update the value
$UpDate="update mytable set Name='$user' where ID=5";
$rtn=$dbh->do($UpDate);
 
print "Table Updated\n\n";
 
###And the delete
$DelUser="delete from mytable where ID=5";
$rtn=$dbh->do($DelUser);
 
print "User Deleted";
 
###Drop the Table
$DropTable="drop table mytable";
$rtn=$dbh->do($DropTable);
 
###Don't forget to close up
$CreateTable->finish();
$dbh->disconnect();