Important alert: (current site time 7/15/2013 8:54:17 PM EDT)
 

VB icon

DBI Connection & Sql Functions

Email
Submitted on: 5/19/2005 4:06:05 AM
By: Darren Wong  
Level: Beginner
User Rating: Unrated
Compatibility: 5.0 (all versions), Active Perl specific, 4.0 (all versions), 3.0 (all versions), Pre 3.0
Views: 9295
 
     Connecting to database using DBI. Example function for Database Query are shown as well ... eg... select, insert, delete and update.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
=**************************************
= Name: DBI Connection & Sql Functions
= Description:Connecting to database using DBI. Example function for Database Query are shown as well ...
eg... select, insert, delete and update.
= By: Darren Wong
=
=This code is copyrighted and has= limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=643&lngWId=6=for details.=**************************************

#######################################################################################################################
# This code shows how to make connection using DBI. Function for each SQL function are implement to ease our life
# Any comment or updates or queries or modification made pls email me at: 
#														
#												wongchinpoh@yahoo.com
#
#######################################################################################################################
#!/usr/bin/perl --
use DBI;
### Function to display the header
sub fMenuHeader()
{
	print "======================================================================\n";
	print "= Start =\n";
	print "======================================================================\n\n";	
}
### Function to display the content or consider as menu
sub fMenuContent()
{
	print "\t\t 1. Select \n";
	print "\t\t 2. Insert \n";
	print "\t\t 3. Update \n";
	print "\t\t 4. Delete \n\n";
	
	print "\t\tEnter which statement to execute:> ";	
}
### Function to display the footer
sub fMenuFooter()
{
	print "======================================================================\n";
	print "= End=\n";
	print "======================================================================\n\n";	
}
### Function to make connection with database
	## Notes * you can makes multiple connection but you requires to change the coding to support function parameter
sub dbConnection()
{
	$dbHost = "localhost";	# Host detail
	$dbName = "training";# Database name to connect
	$dbUser = "root";		# Name to connect to db
	$dbPassword = "";		# Password to connect to db
	
	$dbConnectionInfo = "DBI:mysql:database=$dbName;$dbHost"; # Build Connection string
	
	$dbh = DBI->connect($dbConnectionInfo, $dbUser);# Connect to db
}
$db = &dbConnection();	# Calling above function to make connection with db
### Function to query select statement from database
sub dbSelect($sqlSelect)
{		
	print "\t\tStatement: $sqlSelect \n\n";
	
	$result = $db->prepare($sqlSelect);
	$result->execute();
	
	while(@row = $result->fetchrow())
	{		
		$counter ++;
		print "\t\t$counter) $row[1] \n";	
	}
	
	$result->finish();
}
### Function to query insert data to database
sub dbInsert($sqlInsert)
{
	print "\t\tStatement: $sqlInsert \n\n";
	
	$result = $db->prepare($sqlInsert);
	$result->execute();		
	$result->finish();
}
### Function to query update data from database
sub dbUpdate($sqlUpdate)
{
	print "\t\tStatement: $sqlUpdate \n\n";
	
	$result = $db->prepare($sqlUpdate);
	$result->execute();		
	$result->finish();
}
### Function to query delete data from database
sub dbDelete($sqlDelete)
{
	print "\t\tStatement: $sqlDelete \n\n";
	
	$result = $db->prepare($sqlDelete);
	$result->execute();		
	$result->finish();
}
	fMenuHeader();	# Display header	
	fMenuContent(); # Display content
	$counter = 0;	# Display total record
	
while($statement = <>) # Get user input
{
	# Process Select statement
	if ($statement == 1)
	{		
		print "\n\t\t**********Result***********\n\n";		
		
		$sqlSelect = "SELECT * FROM training";	# Construct Select SQL String
		$execSql = &dbSelect($sqlSelect);		# Execute sql
		
		print "\n";
	}
	
	# Process Select statement
	elsif($statement == 2)
	{
		print "\n\t\t**********Result***********\n\n";		
		
		$sqlInsert = "Insert into training(TrainingDetail, TrainingSts) values('This is for testing', 'Pending')"; # Construct Insert SQL String	
		$execSqlInsert = &dbInsert($sqlInsert); # Execute Sql
		
		### Display new database record
		$sqlSelect = "SELECT * FROM training";
		$execSqlSelect = &dbSelect($sqlSelect);
		
		print "\n";
	}	
	
	elsif($statement == 3)
	{
		print "\n\t\t**********Result***********\n\n";		
		
		$sqlUpdate = "UPDATE training SET TrainingDetail = 'Its Fun Dude - Perl Cool & rules' WHERE TrainingId = 2"; # Construct Update SQL String		
		$execSqlUpdate = &dbUpdate($sqlUpdate); # Execute Sql
		
		### Display new database record
		$sqlSelect = "SELECT * FROM training";
		$execSqlSelect = &dbSelect($sqlSelect);
		
		print "\n";
	}
	
	elsif($statement == 4)
	{
		print "\n\t\t**********Result***********\n\n";		
		
		$sqlDelete = "DELETE FROM training WHERE TrainingDetail = 'This is for testing'"; # Construct Delete SQL String		
		$execSqlDelete = &dbDelete($sqlDelete); # Execute Sql
		
		### Display new database record
		$sqlSelect = "SELECT * FROM training";
		$execSqlSelect = &dbSelect($sqlSelect);
		
		print "\n";
	}
	$counter = 0;
}
fMenuFooter(); # Display the footer


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.