Dave's Brain

Browse - programming tips - perl dbi sql update

Date: 2008jan14
Keywords: SQL, UPDATE, DELETE
Language: perl

Q.  What's the nicest way to do a SQL UPDATE using Perl and DBI?

A.  Since you don't need which reply (from SQL) using the do() method.

	use DB;
	use strict;

	# The way its sometimes done - a bit wordy
	sub wordy($)
	{
		my($dbh) = @_;
		my($sql, $sth, $ref);

    		$sql = qq(UDPATE ...);
		$sth = $dbh->prepare($sql);
		$sth->execute();
        	while ($ref = $sth->fetchrow_hashref())
		{
			# Do nothing
		}
		$sth->finish();
	}

	# A nicer way
	sub nice($$)
	{
		my($dbh, $name) = @_;
		my($sql, $sth, $n_rows);

		$sql = qq(UPDATE ...);
		$n_rows = $dbh->do($sql);
		retun $n_rows;
	}

This works for SQL DELETEs also.

Related
http://www.davekb.com/search.php?target=perl+DBI
http://www.davekb.com/search.php?target=mysql

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.