php 如何在mysql数据库连接中使用抛出异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9836693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:44:28  来源:igfitidea点击:

how to use throw exception in mysql database connect

phpmysqlerror-handlingdatabase-connection

提问by Django Anonymous

I come across this:-

我遇到了这个:-

PHP Error handling: die() Vs trigger_error() Vs throw Exception

PHP 错误处理:die() Vs trigger_error() Vs throw Exception

and understood that throw exception is better

并理解抛出异常更好

How can i replace die and use throw exception here in this code:-

我如何在此代码中替换 die 并在此处使用 throw 异常:-

<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_db = "localhost";
$database_db = "database";
$username_db = "root";
$password_db = "password";
$db = mysqli_connect($hostname_db, $username_db, $password_db) or die("Unable to connect with Database"); 
?>

回答by slash197

try
{
    if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
    {
        //do something
    }
    else
    {
        throw new Exception('Unable to connect');
    }
}
catch(Exception $e)
{
    echo $e->getMessage();
}

回答by burzum

It is documented here http://ie2.php.net/manual/en/mysqli.error.php

它记录在这里http://ie2.php.net/manual/en/mysqli.error.php

if (mysqli_connect_errno()) {
    throw new RuntimeException("Connect failed: %s\n", mysqli_connect_error());
}