我有一个带有约束的表,可防止插入某些变量组合,但是,当我从内部事务执行带有错误值的insert时,插入失败(应该如此),但PDOException
不是提出来了。事实上,事务就好像它成功提交一样,但是下面的select表明没有插入值(仅用于记录,使用相同的函数插入正确的值组合)。出了什么问题?
以下是有问题的功能。 db_SqlSrv::pdo()
创建并返回PDO
的新实例,我正在使用sqlsrv驱动程序。
/**
* Inserts number of rules into <code>menu_availability</code> table.
* The expected format for rules is:
* <code>[{ menu_id: int,
* start: timestring,
* end: timestring,
* weekly: 0..6,
* once: datestring }, ...]</code>
*/
public static function addRules() {
$rules = web_Util::getRequestParam('rules', 'json');
if ($rules !== null) {
$pdo = db_SqlSrv::pdo();
try {
$pdo->beginTransaction();
foreach ($rules as $rule) {
$statement = $pdo->prepare(
"insert into menu_availability
(menu_id, daily_serving_start, daily_serving_end,
weekly_service_off, one_time_service_off)
values (?, ?, ?, ?, ?)");
$statement->bindParam(1, $rule->menu_id, PDO::PARAM_INT);
if ($rule->start) {
$statement->bindParam(2, $rule->start, PDO::PARAM_STR);
$statement->bindParam(3, $rule->end, PDO::PARAM_STR);
} else {
// This feels kind of stupid...
$rule->start = null;
$rule->end = null;
$statement->bindParam(2, $rule->start, PDO::PARAM_NULL);
$statement->bindParam(3, $rule->end, PDO::PARAM_NULL);
}
$statement->bindParam(4, $rule->weekly, PDO::PARAM_INT);
$statement->bindParam(5, $rule->once, PDO::PARAM_STR);
$statement->execute();
}
$pdo->commit();
} catch (PDOException $e) {
$pdo->rollBack();
throw $e;
}
}
return true;
}
这就是表格的定义方式:
if not exists (select * from sysobjects where name = 'menu_availability' and xtype = 'U')
create table menu_availability
(menu_id int not null,
daily_serving_start time(0) null,
daily_serving_end time(0) null,
weekly_service_off tinyint null,
one_time_service_off date null,
sn as case
when ((daily_serving_start is null
and daily_serving_end is null)
and ((weekly_service_off is not null and one_time_service_off is null)
or (one_time_service_off is not null and weekly_service_off is null)))
or
((daily_serving_start is not null
and daily_serving_end is not null)
and (one_time_service_off is null
or weekly_service_off is null))
then cast(1 as bit)
end persisted not null,
constraint ch_valid_week_day
check ((weekly_service_off is null)
or (weekly_service_off <= 6 and weekly_service_off >= 0)));
应触发约束限制的示例数据:
{"menu_id":"18283","start":"","end":"","weekly":3,"once":"16-01-1901"}
(同时授予weekly
和once
答案 0 :(得分:0)
PDO要求您明确告诉它在发生错误时抛出异常。默认情况下,它不会触发错误,也不会抛出异常,它希望您使用PDO::errorCode()
和PDO::errorInfo()
以及PDOStatement
上的等效项手动检查错误。
通过调用PDO::setAttribute()
,您可以更改此行为,通常我会在设置PDO连接时执行此操作:
$db = new PDO($myDSN);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
执行此操作时,PDO会在遇到错误时抛出异常。
值得注意的是,无论此设置如何,连接错误都将始终抛出异常,因为连接是在构造函数中进行的,而异常实际上是解决此问题的唯一方法 - 您显然无法调用对象的方法尚未实例化。这是构造函数通常不应包含业务逻辑的原因之一,它大大降低了这种情况下的灵活性。