65.9K
CodeProject 正在变化。 阅读更多。
Home

通过 Perl 执行 SQL 操作

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (3投票s)

2002 年 9 月 1 日

viewsIcon

158947

本文档解释了如何使用 DBI 模块通过 Perl 对数据库执行操作。

引言

本文档解释了如何使用 DBI 模块通过 Perl 对数据库执行操作。假设您具备 Perl/CGI 和 SQL 的基本知识。我们将创建一个简单的表并对其执行基本的 SQL 操作。

注释

与所有 Perl 代码一样,这段代码也易于理解。如果您需要详细信息,请随时使用文章论坛。

示例一

创建表。

#!/usr/local/bin/perl
use DBI;

$username = '';$password = '';$database = '';$hostname = '';
$dbh = DBI->connect("dbi:mysql:database=$database;" . 
   "host=$hostname;port=3306", $username, $password);

$SQL= "create table user(ID integer primary key " . 
  "auto_increment, username text not null," . 
  " password text not null, email text not null)";

$CreateTable = $dbh->do($SQL);

print "Content-type:text/html\n\n\n";
if($CreateTable){
print "Success";
}
else{
print "Failure<br/>$DBI::errstr";
}

示例二

插入记录。

#!/usr/local/bin/perl
use DBI;

$username = '';$password = '';$database = '';$hostname = '';
$dbh = DBI->connect("dbi:mysql:database=$database;" . 
  "host=$hostname;port=3306", $username, $password);

$SQL= "insert into user (username, password, email)" .
  " values('lexxwern', 'password', 'email@host')";

$InsertRecord = $dbh->do($SQL);

print "Content-type:text/html\n\n\n";
if($InsertRecord){
print "Success";
}
else{
print "Failure<br/>$DBI::errstr";
}

示例三

更新记录。

#!/usr/local/bin/perl
use DBI;

$username = '';$password = '';$database = '';$hostname = '';
$dbh = DBI->connect("dbi:mysql:database=$database;" .
  "host=$hostname;port=3306", $username, $password);

$SQL= "update user set email = ".
  "'lexxwern@yahoo.com' where username = 'lexxwern'";

$UpdateRecord = $dbh->do($SQL);

print "Content-type:text/html\n\n\n";
if($UpdateRecord){
print "Success";
}
else{
print "Failure<br/>$DBI::errstr";
}

示例四

删除记录。

#!/usr/local/bin/perl
use DBI;

$username = '';$password = '';$database = '';$hostname = '';
$dbh = DBI->connect("dbi:mysql:database=$database;" .
  "host=$hostname;port=3306", $username, $password);

$SQL= "delete from user where ID=1";

$DeleteRecord = $dbh->do($SQL);

print "Content-type:text/html\n\n\n";
if($DeleteRecord){
print "Success";
}
else{
print "Failure<br/>$DBI::errstr";
}

示例五

查看所有记录。

#!/usr/local/bin/perl
print "Content-type:text/html\n\n";

use DBI;

$username = '';$password = '';$database = '';$hostname = '';
$dbh = DBI->connect("dbi:mysql:database=$database;" .
 "host=$hostname;port=3306", $username, $password);

$SQL= "select * from user";

$Select = $dbh->prepare($SQL);
$Select->execute();

while($Row=$Select->fetchrow_hashref)
{
  print "$Row->{username}<br/>$Row->{email}";
}

结论

希望这些示例能让您对 DBI 模块的功能有一个清晰的了解。这个网站将提供进一步的帮助。祝你好运!

许可证

本文未附加明确的许可证,但可能在文章文本或下载文件本身中包含使用条款。如有疑问,请通过下面的讨论区联系作者。

作者可能使用的许可证列表可以在此处找到。

© . All rights reserved.