代码之家  ›  专栏  ›  技术社区  ›  Casey

删除前检查表是否存在?

  •  8
  • Casey  · 技术社区  · 15 年前

    我正在检查是否有一张桌子,然后再把它扔了。我已经通读了document\u表的API文档,似乎找不到类似的内容。有什么我不知道的吗?

    我有这样的代码:

    $table = new Doctrine_Table('model_name', $conn);
    
    $export = new Doctrine_Export();
    
    $export->dropTable($table->getTableName());
    

    当一个表不存在时,我得到的错误是:

    提前谢谢,

    4 回复  |  直到 15 年前
        1
  •  27
  •   pleerock    12 年前

    Doctrine2方法是:

    $schemaManager = $this->getDoctrine()->getConnection()->getSchemaManager();
    if ($schemaManager->tablesExist(array('users')) == true) {
          // table exists! ...
    }
    
        2
  •  5
  •   targnation    13 年前

    如果您只想在表存在时返回true/false,我就是这么做的:

    public function checkTable($table)
    {
        $conn = Doctrine_Manager::connection();
        try { $conn->execute("DESC $table"); }
        catch (Exception $e) { return false; }
        return true;
    }
    
        3
  •  2
  •   Casey    15 年前

    这是我最后用的。。。欢迎提出任何改进建议:

    public static function isInstalled()
    {
        $installed = true;
    
        $q = Doctrine_Query::create($conn);
        $q->select('t.id');
        $q->from('Table t'); //the table to check
    
        try {
            $q->execute();
        } catch (Doctrine_Connection_Exception $e) {
            // we only want to silence 'no such table' errors
            if ($e->getPortableCode() !== Doctrine_Core::ERR_NOSUCHTABLE) {
                throw new Doctrine_Export_Exception($e->getMessage());
            }
    
            $installed = false;
        }
    
        return $installed;
    }
    
        4
  •  0
  •   takeshin    15 年前

    我还没有测试可移植性,但在本机SQL中,您可以做到:

    DROP TABLE IF EXISTS ...
    

    您也可以使用条令运行本机SQL查询。

    推荐文章