2016-02-26 75 views
1

如何连接数据库?使用Android连接Sql Azure

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(); 
    } 

} 

错误消息

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的服务器已经允许的IP addresse

回答

0

如果你是在Android上,你不想直接连接到SQL Server。如果你现在有连接字符串,任何人都可以从你的应用程序中获取它,并在你的sql服务器上执行查询。这会将所有数据公开给每个人。你通常在你的android应用程序和你的sql服务器之间放置一个服务器(web服务器)。服务器处理用于保存的安全和业务逻辑等。