简体   繁体   English

Perl-如果表不存在

[英]Perl - If table does not exist

I'm currently using the following which works but throws an error every time the table is created (as it is first trying to insert into a db which does not exist and returning false). 我目前正在使用以下方法,该方法可以正常工作,但每次创建表时都会引发错误(因为它首先尝试插入不存在的数据库中并返回false)。

$result = $dbh->prepare("INSERT INTO `". $host ."` (URL) VALUES ('$href')");
if( ! $result->execute() ){
    $result = $dbh->prepare("CREATE TABLE `" . $host . "` ( `ID` INT( 255 ) NOT NULL AUTO_INCREMENT , `URL` VARCHAR( 255 ) NOT NULL , PRIMARY KEY ( `ID` )) ENGINE = MYISAM ;");
    $result->execute();
    print "Host added: " . $host . "\n";
}

Could someone let me know of a more efficient way of completing this task? 有人可以让我知道完成此任务的更有效方法吗?

EDIT - Bind 编辑-绑定

$result = $dbh->prepare("CREATE TABLE `?` If NOT EXISTS ( `ID` INT( 255 ) NOT NULL AUTO_INCREMENT , `URL` VARCHAR( 255 ) NOT NULL , PRIMARY KEY ( `ID` )) ENGINE = MYISAM ;");
            $result->execute($host);
            $result = $dbh->prepare("INSERT INTO `?` (URL) VALUES ('?')");
            $result->execute($host, $href);
            print "Host added: " . $host . "\n";

is this correct? 这个对吗?

CREATE TABLE Foo if NOT EXISTS  <schema>

另外,请在INSERT操作中使用占位符并绑定值,以免被称为Little Bobby Tables

尝试:

CREATE TABLE tblname IF NOT EXISTS ...

Is this a web app? 这是一个网络应用程序吗? If so, I highly recommend against using a user/pass that has rights to alter the database structure. 如果是这样,我强烈建议您不要使用有权更改数据库结构的用户/密码。 A more typical method would be to have an installer script that creates the tables up front. 一种更典型的方法是使用一个安装程序脚本来预先创建表。

If you expect the table to exist more often than not, the existing code is the most efficient way. 如果您希望表经常存在,那么现有代码最有效的方法。 Note that you can override PrintError and RaiseError (assuming one of those is what you mean by "throws an error") for a given statement handle. 请注意,对于给定的语句句柄,可以覆盖PrintError和RaiseError(假设其中之一是“引发错误”的意思)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM