在Android上使用SQL Server JDBC连接到SQL Server 2012

时间:2018-07-20 05:02:07

标签: java android sql-server jdbc

重要提示:我知道,直接使用JDBC而不是一些众所周知的方法(如REST API)可能不是一个好习惯。但是,由于需求的性质,我确实被迫进行JDBC连接。

重要信息: ANDROID DEVICE VERSION 6.0 API 23

gradle信息(关于sql server)

implementation group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '6.4.0.jre7'

要连接的Java代码:

try {
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    conn = DriverManager.getConnection(connectionUrl, "username", "password");

    ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM myschema.test");

    // Iterate through the data in the result set and display it.
    while (rs.next()) {
        System.out.println("test result: " + rs.getInt(0));
    }
} catch (ClassNotFoundException | SQLException e) {
    e.printStackTrace();
}

我尝试对连接字符串使用不同的参数,例如crypto = false或authentication = SqlPassword无效。修改了SQLServer上的配置,以便能够使用sqlcmd进行远程连接

这是使用的当前连接字符串

private String connectionUrl = "jdbc:sqlserver://192.168.0.105:1433;" +
        "databaseName=dbname";

这有效

sqlcmd -S 192.168.0.105 -U user -P pass

这不是

sqlcmd -S 192.168.0.105\SQLSERVER2012 -U user -P pass

这就是我正在努力的目标:

07-20 01:58:06.013 13031-13031/com.mycompany.myproject W/System.err: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "Socket closed". ClientConnectionId:76a6a26c-a11f-46d1-806d-dd9fbd89491a
07-20 01:58:06.023 13031-13031/com.mycompany.myproject W/System.err:     at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2670)
        at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1837)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2257)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1921)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1762)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1077)
        at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:618)
        at java.sql.DriverManager.getConnection(DriverManager.java:179)
        at java.sql.DriverManager.getConnection(DriverManager.java:213)
        at com.mycompany.myproject.database.SQLDatabaseConnection.<init>(SQLDatabaseConnection.java:23)
        at com.mycompany.myproject.activities.MainActivity.onCreate(MainActivity.java:53)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    Caused by: java.net.SocketException: Socket closed
07-20 01:58:06.033 13031-13031/com.mycompany.myproject W/System.err:     at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
        at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:324)
        at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1767)
        ... 21 more

在阅读之后,我并没有真正发现如何解决这个问题,因此我能够执行该查询。

这是由SSL引起的吗?可能与网络问题有关吗?您建议如何解决此问题,以便我可以执行此查询?

1 个答案:

答案 0 :(得分:-1)

我已经在android 7.0中做到了,它工作正常。 Si nececitasmásayuda o no te sirvio,avisame,坦比昂大豆(tambiénsoy de arg)

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

            connection = DriverManager.getConnection("jdbc:jtds:sqlserver://dbIP:port//DbName", "User", "Password");       // Connect to database
            if (connection == null) {
                ConnectionResult = "Verifica tu conexión a internet"; //handle connection
                Toast.makeText(activity, ConnectionResult, Toast.LENGTH_LONG).show();
            } else {
                   //execute  query
                codigo.toUpperCase();
                ResultSet rs = null;
                String query = "EXEC AppMovil.INITE_Articulos_Familia '" + codigo  + "'";
                Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);


                //size = cantidad de rows, metodo para obtener cantidad de rows
                rs = stmt.executeQuery(query);
                ResultSetMetaData rsmtd = rs.getMetaData();
                while(rs.next()){
                    ListaConsultaFamilia item = new ListaConsultaFamilia(
                            rs.getString("Codigo"),
                            rs.getString("Descripcion"),
                            rs.getString("Precio")
                    );
                    listaConsultaFamilias.add(item);
                }

                listaConsultaFamilias.size();

                ConnectionResult = " successful";
                isSuccess = true;


                connection.close();
            }

        }catch (Exception ex)
        {
          //catch error while reading
            Looper.prepare();
            isSuccess = false;
            Toast.makeText(activity, "No existen consultas en el periodo seleccionado", Toast.LENGTH_LONG).show();
            ConnectionResult = ex.getMessage();
        }