PDOException:SQLSTATE[IM002] SQLDriverConnect:0 [unixODBC][驱动程序管理器]未找到数据源名称,且未指定默认驱动程序,位于 /var/www/app/src/Database/OdbcConnector.php 第 21 行
PDOException: SQLSTATE[IM002] SQLDriverConnect: 0 [unixODBC][Driver Manager]Data source name not found, and no default driver specified in /var/www/app/src/Database/OdbcConnector.php on line 21
ID: php/pdo-odbc-connection-string-malformed
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| PHP 8.1.30 | active | — | — | — |
| PHP 8.2.18 | active | — | — | — |
| unixODBC 2.3.12 | active | — | — | — |
根因分析
ODBC 连接字符串引用了未在 odbc.ini 或 /etc/odbc.ini 中定义的 DSN,或者系统上未安装/配置所需的 ODBC 驱动程序。
English
ODBC connection string references a DSN that is not defined in odbc.ini or /etc/odbc.ini, or the required ODBC driver is not installed/configured on the system.
官方文档
https://www.php.net/manual/en/ref.pdo-odbc.connection.php解决方案
-
Verify DSN configuration: odbcinst -j shows config files; check /etc/odbc.ini for [MyDSN] section with Driver= and Server= entries. Add missing DSN: echo -e '[MyDSN]\nDriver=PostgreSQL Unicode\nServer=localhost\nPort=5432\nDatabase=mydb' >> /etc/odbc.ini
-
Use a full connection string without DSN: $pdo = new PDO('odbc:Driver={PostgreSQL Unicode};Server=localhost;Port=5432;Database=mydb;Uid=user;Pwd=pass;');
无效尝试
常见但无效的做法:
-
75% 失败
Installing only the ODBC driver (e.g., psqlodbc for PostgreSQL) without configuring the DSN in odbc.ini still results in the same error because the driver is not associated with a DSN name.
-
60% 失败
Using a DSN name with spaces or special characters without quoting it in the connection string causes the driver manager to parse it incorrectly.