简体   繁体   中英

Connect Sql Azure with Android

How can I connect database?

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

String connectionString = "jdbc:sqlserver://xxxxx.database.windows.net:1433;database=navili;user=xxxxxx;password=xxxxx;encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
PreparedStatement prepsInsertPerson = null;
PreparedStatement prepsUpdateAge = null;

try {

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

    connection = DriverManager.getConnection(connectionString);
    /*String selectSql = "SELECT Username, Password FROM dbo.System_Users";
    statement = connection.createStatement();
    resultSet = statement.executeQuery(selectSql);*/

    // Iterate through the result set and print the attributes.
    /*while (resultSet.next()) {
        System.out.println(resultSet.getString(2) + " "
                + resultSet.getString(3));
    }*/
}
catch (Exception e) {
    e.printStackTrace();
}
finally {
    // Close the connections after the data has been handled.
    if (prepsInsertPerson != null) try { prepsInsertPerson.close(); } catch(Exception e) {}
    if (prepsUpdateAge != null) try { prepsUpdateAge.close(); } catch(Exception e) {}
    if (resultSet != null) try { resultSet.close(); } catch(Exception e) {}
    if (statement != null) try { statement.close(); } catch(Exception e) {}
    if (connection != null) try {
        Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_LONG).show();
        connection.close();} catch(Exception e) {}
    else{
        Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
    }

}

Error Message

com.example.tao.navi 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".

Azure Server already allowed ip addresse

If you are on android you do not want to connect to a sql server directly. When you have the connection string like you have now, anybody can get it from your application and do queries on you sql server. This will expose all you data to everyone. You normally put a server (web server) between you android application and your sql server. The server handles the security and business logic for saving etc.

Try putting this at the end of your connection URL ;ssl=request

And if your are using jtds libraries then also add jtds: after jdbc: in your connection url

and also change database=navili; to DatabaseName=navili;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM