首先,要安装perl的DBI模块,目前最新的版本是1.14,可以去www.cpan.org下载,文件名是DBI-1.14.tar.gz,下载后将该文件拷贝到一个临时目录中,运行以下命令安装: tar xzvf DBI-1.14.tar.gz cd DBI-1.14 perl Makefile.PL make make test make install 然后,要安装Msql-Mysql-modules,我得到的最新版本是1.2215,可以去www.cpan.org下载,文件名是Msql-Mysql-modules-1.2215.tar.gz,下载后将该文件拷贝到一个临时目录中,运行以下命令安装: tar xzvf Msql-Mysql-modules-1.2215.tar.gz cd Msql-Mysql-modules-1.2215 perl Makefile.PL make make test make install 执行“perl Makefile.PL”命令时会提示你输入选项,如果是值用来支持Mysql的话,输入1就可以了。 需要的软件安装完成,现在就可以在perl程序中连接数据库了。 use DBI; #这条语句是用来说明使用DBI模块的 my $dsn="DBI:mysql:$db_name:$host"; #这条语句用来定义一个数据源,其中$db_name是你要连接的数据库的库名,$host是你要连接的数据库所在的主机名,可以省略不写,用这种形式:my $dsn="DBI:mysql:$db_name"; my $db_user="db_username"; my $db_pass="db_password"; #这里定义了连接数据库时使用的用户名和密码 my ($dbh,$sth);#定义两个标量,用来做库句柄和语句句柄 $dbh=DBI->connect($dsn,$db_user,$db_pass,{RaiseError=>1}); #使用面向对象的方法建立一个数据库句柄,其中“RaiseError=>1”的作用是连接数据库出错时显示一条信息,然后退出,如果不用这种方法的话,DBI->connect方法将返回一个undef值。这时,我们就可以进行数据库的操作了。 #下面,我将介绍两种数据库操作的方法 1.有返回值的处理方法 $sth=$dbh->prepare("select password from userinformation where username='$username'"); #输入一条SQL语句 $sth->execute(); #执行SQL语句 my $password=$sth->fetchrow_array(); # -- or -- while(my @password=$sth->fetchrow_array()) { ... } #得到查询的返回结果,如果是多个值的话,可以使用while循环来做。 $sth->finish(); #关闭语句句柄 2.无返回值的处理方法 my $stat=$dbh->do("insert into userinformation values('$username','$password','$state')"); #这种无返回值的处理方法就简单多了,也不用使用$sth->finish();语句来关闭数据库句柄 $dbh->disconnect(); #关闭数据库句柄 这就是连接数据库的基本操作,但是,使用过程中要注意一些问题: 1.使用do的方法时,后面不要跟$sth->finish();语句 2.连接数据库完毕后,要记得关闭数据库句柄,即执行$dbh->disconnect();语句 |