php - 检查数据库表是否存在 - 性能?

标签 php mysql

我想为未指定的框架/系统制作一些简单的对象/模型。

此外,我想使用 MySQL 作为我的数据的后端。

我的目标是简单的实现 - 对配置文件进行小的更改,基本上就是这样。

我的问题是,我确信在使用模型时需要检查数据库表是否确实存在 - 如果不存在,请为我创建表。

我在想这样的事情:

<?php

  class MyObject
  {

    public function __construct()
    {
      $dal->query("SHOW TABLES LIKE 'MyTable'");

      if($dal->num_rows() == 0)
        $this->_createTables();
    }
    ...
  }
?>

但我担心此模型的性能 - 我正在寻找对我的解决方案效率的确认或更好的解决方案。

最佳答案

在我看来,根据您的应用程序的需求,您最好仅在发生错误时检查此条件,否则假设该表存在。这样的事情可以避免对每个实例进行额外的查询(但是,您应该将检查放入其自己的方法中)。

public function insert($data, $spiralingToDeath=false)
{
  // (do actual insertion here)

  if ($this->isError) {
    // nothing obvious

    if ($spiralingToDeath) {
      // recursion check
      throw new DBException("Tried to create a table and failed.");
    } else {
      $dal->query("SHOW TABLES LIKE 'MyTable'");

      if($dal->num_rows() == 0) {
         $this->_createTables();
      } 
      // try again:
      $this->insert($data, true);
   }
 }
}

关于php - 检查数据库表是否存在 - 性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4478980/

相关文章:

mysql - Lazarus 插入 sql 结果 int 字符串网格

php - 不使用Drupal CMS的views_slideshow

php - 使用 PHP json_encode 解析错误

php - 检查字符串是否为unix时间戳

php - Yii:为什么我的 Controller 默认索引不起作用?

mysql - 在 phpmyadmin 中执行准备好的语句查询时遇到问题

mysql - phpmyadmin 插入 DOB

sql - mysql中,存储过程效率更高吗?

Mysql:用外键删除两个表中的行

php - 同时使用 count(*) 和 mysql_fetch_object()?