我正在尝试学习使用PDO方法来访问mysql数据库。在下面的代码示例中,我创建了一个测试程序,在没有异常时工作正常。为了生成异常,我在表中添加了一个强制的第三个字段,以便execute语句失败。我希望做的是测试'catch'分支,但在尝试了几个不同的东西后,我总是从该行得到一个'未捕获的异常错误',例如:
致命错误:带有消息'SQLSTATE [HY000]的未捕获异常'PDOException':常规错误:1364字段'Tst_integer'在/var/www/ccc/ccc/cccccy/zztest.php中没有默认值' :46
第46行对应于执行语句。
为什么没有触发异常?
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
class pdo_connect {
var $pdo_con;
var $message;
function __construct(){
$cur_date = date('Y-m-d H:i:s');
$BDconfig = array(
'host' => 'localhost',
'user' => 'p2p_user',
'pass' => 'keith1',
'dbname' => 'p2p_notes_data'
);
$db_host = $BDconfig['host'];
$db_user = $BDconfig['user'];
$db_pass = $BDconfig['pass'];
$db_name = $BDconfig['dbname'];
$dsn = 'mysql:dbname='. $db_name . ';' . 'host=' . $db_host;
// mysql connect information, pass
try{
$this->pdo_con = new PDO ($dsn, $db_user, $db_pass);
$this->pdo_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$this->pdo_con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (\PDOException $e) {
echo '$cur_date' . " " . 'Connection failed: ' . $e->getMessage() . PHP_EOL;
die();
}
}
function __destruct(){
$this->pdo_con = null;
}
}
$dbh = new pdo_connect;
//$dbh->pdo_con->beginTransaction();
$field1 = date('Y-m-d H:i:s');
$field2 = 'mytst';
$sth = $dbh->pdo_con->prepare("INSERT INTO test_table (Tst_Date,Tst_String) VALUES (:field1,:field2);");
try {
$sth->execute(array(":field1" => $field1, ":field2" => $field2));
} catch (PDOExeption $e) {
//$dbh->pdo_con->rollBack();
echo $e->getMessage();
echo 'ttttt', PHP_EOL;
}
//$dbh->pdo_con->commit();
?>
答案 0 :(得分:3)
你有一个错字
PDOExeption
^-- missed c