我想为未指定的框架/系统制作一些简单的对象/模型。
此外,我想使用 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/