gpt4 book ai didi

php - 执行多个查询时的 Doctrine (DBAL) 错误处理

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:49:37 24 4
gpt4 key购买 nike

我有一个模式 sql 文件(有语法错误),包括对设置数据库的多个查询

example.sql

CREATE TABLE IF NOT EXISTS `example` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;


CREATExxxxxxxxxx TABLE IF NOT EXISTS `example2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

example.php

$sqlContent = file_get_contents("example.sql");
$stmt = $conn->prepare($sqlContent);
$result = $stmt->execute();

即使我的 sql 不正确,execute 方法也不会抛出任何异常。它的文档说它在失败时返回 false 但它返回 true

这里应该如何进行异常处理?如何检查我的查询是否有错误?

最佳答案

问题不在 Doctrine DBAL 中,而在 PDO 中。如果您将驱动程序更改为 mysqli(而不是 pdo_mysql),那么您将收到如下错误消息:

[Doctrine\DBAL\Exception\SyntaxErrorException]
An exception occurred while executing 'CREATE TABLE IF NOT EXISTS example (

`id` int(11) NOT NULL AUTO_INCREMENT,                                                                                                                                                   
`name` text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

AUTO_INCREMENT=1 ;
CREATExxxxxxxxxx TABLE IF NOT EXISTS example2 (

`id` int(11) NOT NULL AUTO_INCREMENT,                                                                                                                                                   
`name` text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

AUTO_INCREMENT=1 ;':
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATExxxxxxxxxx TABLE IF NOT EXISTS example2 (
id int(11) NOT NULL AUTO_I' at line 8

如果您直接使用 PDO(而不是通过 Doctrine),那么您也不会收到错误。

如果您希望它能正常工作,那么您必须禁用准备好的语句的模拟(将 PDO::ATTR_EMULATE_PREPARES 设置为 0)。

关于php - 执行多个查询时的 Doctrine (DBAL) 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34766314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com