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

Android Studio中使用最新JDBC驱动连接MS SQL Server失败求助

Android下使用微软官方JDBC驱动连接SQL Server的解决方案

核心问题

微软最新的mssql-jdbc驱动基于标准Java SE开发,而Android的ART/Dalvik运行时与Java SE存在特性差异,部分高版本驱动依赖的Java 11+特性Android无法支持,同时网络安全配置、权限等也会导致连接失败。

具体解决步骤

  1. 选择兼容Android的驱动版本
    高版本mssql-jdbc(10.0+)要求Java 11+,Android对其兼容性差,建议使用JRE8兼容的最高稳定版本,在Module级build.gradle中添加依赖:

    dependencies {
        implementation 'com.microsoft.sqlserver:mssql-jdbc:9.4.1.jre8'
    }
    
  2. 完善代码异常捕获与参数配置
    原代码仅捕获了ClassNotFoundException,缺失SQLException会导致无法定位具体连接失败原因,同时添加encrypt=false关闭默认加密(Android环境下证书验证易出问题):

    private Connection connection;
    private Statement statement;
    
    public void connect() {
        try {
            String url = "jdbc:sqlserver://YOUR_SERVER:YOUR_PORT;databaseName=YOUR_DATABASE;user=YOUR_USERNAME;password=YOUR_PASSWORD;encrypt=false";
            // Android 6.0+ 无需显式加载驱动,DriverManager会自动扫描
            connection = DriverManager.getConnection(url);
            statement = connection.createStatement();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace(); // 此处可通过Log打印详细错误信息
        }
    }
    
  3. 配置网络权限与安全策略

    • 在AndroidManifest.xml中添加网络权限:
      <uses-permission android:name="android.permission.INTERNET" />
      
    • Android 9.0+默认禁止明文网络请求,若SQL Server未配置SSL,需创建res/xml/network_security_config.xml:
      <?xml version="1.0" encoding="utf-8"?>
      <network-security-config>
          <domain-config cleartextTrafficPermitted="true">
              <domain includeSubdomains="true">你的服务器IP或域名</domain>
          </domain-config>
      </network-security-config>
      
      并在AndroidManifest.xml的application标签中引用:
      <application
          ...
          android:networkSecurityConfig="@xml/network_security_config">
      

排查关键

运行代码后查看SQLException的详细堆栈信息,常见失败原因包括:

  • 驱动版本不兼容(报错类未找到或方法不存在)
  • 服务器端口/IP配置错误(连接超时)
  • 网络权限未授予
  • 加密连接验证失败(需调整encrypt或trustServerCertificate参数)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 21:39:59