codeigniter 连接 postgresql 的核心是正确配置驱动(ci3 用 postgre,ci4 用 pgsql)、启用 pgsql/pdo_pgsql 扩展、设置 hostname/username/password/database/port 等参数,并确保 postgresql 服务运行且用户有库访问权限。

CodeIgniter 连接 PostgreSQL 数据库,核心是正确配置数据库驱动和连接参数,并确保环境支持。它不像 MySQL 那样开箱即用,需要额外注意扩展、驱动名和部分参数兼容性。
确认 PHP 环境已启用 PostgreSQL 扩展
PostgreSQL 连接依赖 pgsql 或 pdo_pgsql 扩展(推荐 pgsql)。在终端运行:
php -m | grep -i "pgsql"
若无输出,需启用扩展:编辑 php.ini,取消注释或添加:
extension=pgsql extension=pdo_pgsql
重启 Web 服务(如 Apache/Nginx)后生效。
配置 application/config/database.php
将 $db['default'] 的驱动设为 postgre(CI3)或 pgsql(CI4),其他关键项示例如下:
-
hostname:数据库服务器地址(如
localhost或 IP) -
username 和 password:PostgreSQL 用户凭据(注意:默认用户常为
postgres) - database:已创建的目标数据库名(不能是空字符串)
-
port:默认
5432,若自定义需显式指定(CI3 中需加到配置数组里) -
dbdriver:
"postgre"(CI3)、"pgsql"(CI4) -
char_set 和 dbcollat:建议设为
"utf8"和"en_US.UTF-8"或"utf8mb4_general_ci"(实际以 PostgreSQL locale 为准)
CI3 示例片段:
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'postgres',
'password' => 'your_password',
'database' => 'myapp_db',
'dbdriver' => 'postgre',
'port' => 5432,
'char_set' => 'utf8',
'dbcollat' => 'en_US.UTF-8',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'stricton' => FALSE,
'failover' => array()
);
加载并测试连接
在控制器中手动加载数据库并验证是否连通:
// CI3 中
$this->load->database();
// 测试查询(非空结果说明连接有效)
$query = $this->db->query("SELECT version()");
if ($query && $query->num_rows() > 0) {
echo $query->row()->version;
} else {
show_error('PostgreSQL 连接失败,请检查配置与服务状态');
}
更稳妥的方式是捕获异常(尤其 CI4):
- CI4 使用
try/catch捕获ConnectionException - 确保 PostgreSQL 服务正在运行:
sudo systemctl status postgresql - 确认用户有权限访问目标数据库:
psql -U postgres -d myapp_db
常见报错与处理
遇到连接失败时,优先排查以下几点:
-
"Unable to connect to your database server using the provided settings." → 检查
dbdriver是否拼写为postgre(CI3)或pgsql(CI4),不是postgresql -
"FATAL: database "xxx" does not exist" → 数据库未创建,用
createdb -U postgres myapp_db创建 -
"pg_connect(): Unable to connect..." → PHP 扩展未启用,或 PostgreSQL 未监听本地连接(检查
postgresql.conf中listen_addresses和pg_hba.conf认证规则) -
中文乱码 → 确保
char_set与数据库实际编码一致,且建库时指定了 UTF8 locale
不复杂但容易忽略。











