Android 上的 Postgresql JDBC 连接错误

Postgresql JDBC connection error on Android

我无法在 Android 上连接 PostgreSQL 数据库。使用 JDBC 仅用于开发目的,将更改为适当的网络服务。

  1. 我已经在 build.gradle 中将 PostgreSQL 驱动程序实现为“实现 'org.postgresql:postgresql:42.2.18.jre7”
  2. 我的 PostgreSQL 数据库服务器正在侦听端口:5433
  3. 我的电脑IP在我的网络是192.168.1.103
  4. 并且用户名和密码设置正确

连接:

Connection con = null;
try
{
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    /* Register jdbc driver class. */
    Class.forName("org.postgresql.Driver");

    /* Create connection url. */
    String postgresConnUrl = "jdbc:postgresql://192.168.1.103:5433/lmsdb";

    Properties props = new Properties();
    props.setProperty("user","postgres");
    props.setProperty("password","xxxxxxx");
    props.setProperty("ssl","false");

    /* Get the Connection object. */
    con = DriverManager.getConnection(postgresConnUrl, props);
}catch(Exception ex)
{
    ex.printStackTrace();
}finally
{
    return con ;
}

当我将“postgresConnUrl”中的 IP 更改为 pg_hba 中设置的 127.0.0.1 时,出现错误

org.postgresql.util.PSQLException: Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

并且当我如上面的连接代码所示使用计算机的 IP 地址时,连接 con = DriverManager.getConnection(postgresConnUrl, props); 返回 null。日志显示没有异常或错误,但 con 为空,我无法追踪问题。对问题的任何指示都会有所帮助。

DriverManager.getConnection(...)不能returnnull。除非在实现中存在严重错误,否则它总是 returns 一个 non-null 连接 抛出一个 SQLException (或 RuntimeExceptionError 由 drivers 抛出)。

PostgreSQL driver 可能导致抛出 Error(例如 NoClassDefFoundError,因为 PostgreSQL JDBC driver 使用 Java 功能或 类 在 Android 上不存在)。这是隐藏的,因为你的 finally 块将无条件地 return con,并且你只捕获和记录 Exception 的实例,而不是 Error。另见 Adding return in finally hides the exception

删除你的 catchfinally 块,让任何异常或其他 Throwable 冒泡到调用者,而不是用隐藏错误替换显式异常或错误 (returning null),或者让 catch 块 wrap 自定义异常中的异常并抛出该自定义异常。

我建议您不要在 Android 上使用 JDBC。最近的 JDBC driver 正在使用 Java 功能或 Android 上不存在的 类,这可能会导致各种问题。你提到你这样做是为了开发目的,但我建议创建或模拟你的 REST API 并从一开始就使用它会为你省去很多麻烦和不必要的开发工作。

我尝试使用旧版本的 JDBC 并且能够连接。 JDBC 的较新版本似乎与 Android 不兼容,导致您发布时出现错误。但是,我仍然可以看到很多人在使用 JDBC,因为它很容易,尽管休息 API 是更好的选择,但需要额外的技能。