Snippet Name: SQL Insert Example
Description: Here we add two records to the database using an INSERT statement. The data to be entered can be gathered from an HTML form.
Comment: (none)
Language: PERL
Highlight Mode: PERL
Last Modified: March 05th, 2009
|
#!/usr/bin/perl
# Use the DBI module
USE DBI QW(:sql_types);
# Declare local variables
MY ($databaseName, $databaseUser, $databasePw, $dbh);
MY ($stmt, sth, @newRow);
MY ($telephone);
# Set the parameter values for the connection
$databaseName = "DBI:mysql:yourWebSite_com";
$databaseUser = "yourLoginId";
$databasePw = "yourLoginPassword";
# Connect to the database
# Note this connection can be used to
# execute more than one statement
# on any number of tables in the database
$dbh = DBI->connect($databaseName, $databaseUser,
$databasePw) || DIE "Connect failed: $DBI::errstr\n";
# Create the statement.
$stmt = "INSERT INTO Phonebook (Id, Name, Telephone)
VALUES (‘BBBBB', ‘Joe Smith', ‘212-555-1212')";
# Prepare and execute the SQL query
$sth = $$dbh->prepare($$stmt)
|| DIE "prepare: $$stmt: $DBI::errstr";
$sth->execute || DIE "execute: $$stmt: $DBI::errstr";
# INSERT does not return records
# Clean up the record set
$sth->finish();
# We could add another record here as well
# Create the statement.
$stmt = "INSERT INTO Phonebook (Id, Name, Telephone) VALUES (‘CCCCC', ‘Marcy Jones', ‘402-555-1212')";
# Prepare and execute the SQL query $sth =
$$dbh->prepare($$stmt)
|| DIE "prepare: $$stmt: $DBI::errstr";
$sth->execute || DIE "execute: $$stmt: $DBI::errstr";
# Clean up the record set and the database connection
$sth->finish();
$dbh->disconnect(); |