You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS Swift应用连接CockroachDB遇连接拒绝问题求助

iOS连接CockroachDB问题解决及可行方案

有不少开发者成功用PostgresClientKit或其他Swift库实现iOS应用与CockroachDB的数据交互,你遇到的connection refused错误可以从以下几个方向排查修复:

错误原因分析

你遇到的codeProxyRefusedConnection错误大概率是配置错误或网络访问限制导致的,结合你的代码来看,存在几个明显问题:

  • 数据库名称配置错误:configuration.database字段应该填写CockroachDB集群中的数据库名(比如默认的defaultdb),而非server.table这种格式,表的指定应该写在SQL查询语句中。
  • 未开启SSL连接:CockroachDB Cloud强制要求SSL连接,你的代码中缺少SSL相关配置。
  • IP访问限制:CockroachDB Cloud集群默认只允许添加到白名单的IP访问,你的iOS设备公网IP可能未被授权。

修正后的PostgresClientKit连接代码

import PostgresClientKit

do {
    var configuration = PostgresClientKit.ConnectionConfiguration()
    configuration.host = "host.cockroachlabs.cloud"
    configuration.database = "defaultdb" // 替换为你的CockroachDB数据库名
    configuration.user = "username@cluster-name" // 注意格式:用户名@集群名称
    configuration.port = 26257 // 替换为你的集群实际端口(通常是26257)
    configuration.credential = .scramSHA256(password: "your-password")
    
    // 强制开启SSL,CockroachDB Cloud必须配置
    configuration.ssl = .require
    
    // 可选:添加根证书验证(需先下载CockroachDB根证书到项目中)
    if let certPath = Bundle.main.path(forResource: "root", ofType: "crt") {
        configuration.sslRootCertificatePath = certPath
    }
    
    let connection = try PostgresClientKit.Connection(configuration: configuration)
    defer { connection.close() }
    
    // 测试连接的查询语句
    let statement = try connection.prepareStatement(text: "SELECT * FROM public.your-table-name")
    defer { statement.close() }
    
    let cursor = try statement.execute()
    for row in cursor {
        let columns = try row.get()
        // 处理查询结果
        print("查询结果:\(columns)")
    }
} catch {
    print("连接或查询错误:\(error.localizedDescription)")
}

必要的额外配置

  • IP白名单设置:登录CockroachDB Cloud控制台,找到你的集群,进入「Networking」页面,将iOS设备当前的公网IP加入允许访问列表(测试阶段可临时允许0.0.0.0/0,生产环境务必限制特定IP)。
  • 根证书获取:可从CockroachDB Cloud集群的连接详情页面下载根证书,将其添加到iOS项目中,并确保在Build Phases的Copy Bundle Resources中包含该文件。

替代库推荐

如果PostgresClientKit仍有问题,可尝试这些Swift库:

  • PostgresNIO:基于SwiftNIO的异步PostgreSQL客户端,性能优异,适合现代iOS异步编程场景。
  • GRDB:轻量级ORM库,支持PostgreSQL(兼容CockroachDB),提供便捷的数据持久化和查询API。

内容的提问来源于stack exchange,提问作者la44578

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 09:33:28