简体   繁体   English

MySQL 检查表是否存在而不抛出异常

[英]MySQL check if a table exists without throwing an exception

What is the best way to check if a table exists in MySQL (preferably via PDO in PHP) without throwing an exception.检查 MySQL 中是否存在表(最好通过 PHP 中的 PDO)而不抛出异常的最佳方法是什么。 I do not feel like parsing the results of "SHOW TABLES LIKE" et cetera.我不想解析“SHOW TABLES LIKE”等的结果。 There must be some sort of boolean query?一定有某种 boolean 查询?

Querying the information_schema database using prepared statement looks like the most reliable and secure solution.使用准备好的语句查询 information_schema 数据库看起来是最可靠和安全的解决方案。

 $sql = "SELECT 1 FROM information_schema.tables WHERE table_schema = database() AND table_name =?"; $stmt = $pdo->prepare($sql); $stmt->execute([$tableName]); $exists = (bool)$stmt->fetchColumn();

If you're using MySQL 5.0 and later, you could try:如果您使用的是 MySQL 5.0 及更高版本,您可以尝试:

 SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '[database name]' AND table_name = '[table name]';

Any results indicate the table exists.任何结果都表明该表存在。

From: http://www.electrictoolbox.com/check-if-mysql-table-exists/来自: http://www.electrictoolbox.com/check-if-mysql-table-exists/

Using mysqli I've created following function.使用 mysqli 我在 function 之后创建。 Assuming you have an mysqli instance called $con.假设您有一个名为 $con 的 mysqli 实例。

 function table_exist($con, $table){ $table = $con->real_escape_string($table); $sql = "show tables like '".$table."'"; $res = $con->query($sql); return ($res->num_rows > 0); }

Hope it helps.希望能帮助到你。

Warning: as sugested by @jcaron this function could be vulnerable to sqlinjection attacs, so make sure your $table var is clean or even better use parameterised queries.警告:正如@jcaron 所建议的,这个 function 可能容易受到 sqlinjection 攻击,因此请确保您的$table var 是干净的,或者更好地使用参数化查询。

This is posted simply if anyone comes looking for this question.如果有人来寻找这个问题,就会简单地发布这个。 Even though its been answered a bit.即使它被回答了一点。 Some of the replies make it more complex than it needed to be.一些回复使它比它需要的更复杂。

For mysql* I used:对于 mysql* 我使用:

 if (mysqli_num_rows( mysqli_query( $con,"SHOW TABLES LIKE '". $table. "'") ) > 0 or die ("No table set") ){

In PDO I used:在 PDO 我使用:

 if ($con->query( "SHOW TABLES LIKE '". $table. "'" )->rowCount() > 0 or die("No table set") ){

With this I just push the else condition into or.有了这个,我只是将 else 条件推入 or 。 And for my needs I only simply need die.为了我的需要,我只需要死。 Though you can set or to other things.虽然你可以设置或其他的东西。 Some might prefer the if/ else if/else.有些人可能更喜欢 if/else if/else。 Which is then to remove or and then supply if/else if/else.然后删除 or 然后提供 if/else if/else。

Here is the my solution that I prefer when using stored procedures.这是我在使用存储过程时更喜欢的解决方案。 Custom mysql function for check the table exists in current database.自定义 mysql function 用于检查当前数据库中是否存在该表。

 delimiter $$ CREATE FUNCTION TABLE_EXISTS(_table_name VARCHAR(45)) RETURNS BOOLEAN DETERMINISTIC READS SQL DATA BEGIN DECLARE _exists TINYINT(1) DEFAULT 0; SELECT COUNT(*) INTO _exists FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = _table_name; RETURN _exists; END$$ SELECT TABLE_EXISTS('you_table_name') as _exists

As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result由于“显示表”在大型数据库上可能会很慢,我建议使用“DESCRIBE”并检查结果是否为真/假

$tableExists = mysqli_query("DESCRIBE `myTable`");
$q = "SHOW TABLES"; $res = mysql_query($q, $con); if ($res) while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) ) { foreach( $row as $key => $value ) { if ( $value = BTABLE ) // BTABLE IS A DEFINED NAME OF TABLE echo "exist"; else echo "not exist"; } }

Zend framework Zend 框架

public function verifyTablesExists($tablesName) { $db = $this->getDefaultAdapter(); $config_db = $db->getConfig(); $sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}' AND table_name = '{$tablesName}'"; $result = $db->fetchRow($sql); return $result; }

If the reason for wanting to do this is is conditional table creation, then 'CREATE TABLE IF NOT EXISTS' seems ideal for the job.如果想要这样做的原因是有条件的表创建,那么“CREATE TABLE IF NOT EXISTS”似乎是这项工作的理想选择。 Until I discovered this, I used the 'DESCRIBE' method above.在我发现这一点之前,我使用了上面的“DESCRIBE”方法。 More info here: MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050更多信息在这里: MySQL“如果不存在则创建表”-> 错误 1050

Why you make it so hard to understand?为什么让你这么难理解?

 function table_exist($table){ $pTableExist = mysql_query("show tables like '".$table."'"); if ($rTableExist = mysql_fetch_array($pTableExist)) { return "Yes"; }else{ return "No"; } }

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

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