将SQL Azure与Android连接

时间:2012-03-21 06:23:51

标签: java android azure azure-sql-database

我正在尝试从我的Android应用程序连接SQL Azure。该代码适用于Java应用程序,我设法从SQL Azure获取数据,但它为我的android抛出错误。以下是我的代码和错误消息 代码:

String connectionString =
                    "jdbc:sqlserver://serversql.database.windows.net:1433" + ";" +  
                "database=dbname    " + ";" + 
                "user=user@serversql" + ";" +  
                "password=password";
            Connection connection = null;  // For making the connection
            Statement statement = null;    // For the SQL statement 
            ResultSet resultSet = null;    // For the result set, if applicable 
        try
        {

            // Ensure the SQL Server driver class is available.
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");              
            // Establish the connection.
            connection = DriverManager.getConnection(connectionString);
            String filename = "SVPoster.jpg";
            String sql = "Select * from VoucherTable";
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            int count;
            if(resultSet.next())
            {
                Blob test = resultSet.getBlob("Voucher"); 
                InputStream x=test.getBinaryStream();
                int size=x.available();
                OutputStream output = new FileOutputStream("/sdcard/"
                        + filename);
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = x.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }
                output.flush();
                output.close();
                x.close();
            }               
        }
        catch (Exception ex)
        {
            Toast.makeText(getApplicationContext(), ex.toString(),
                     Toast.LENGTH_LONG).show();
        }

错误消息

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host server.database.windows.net, port 1433 has failed. Error: "null. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".

1 个答案:

答案 0 :(得分:0)

这很可能是因为SQL Azure防火墙。您可能需要打开它才能使用它:

https://msdn.microsoft.com/en-us/library/azure/jj553530.aspx

由于您不知道Android应用的IP地址,我认为选择是:

  • 完全打开防火墙(从0.0.0.0开始,结束于255.255.255.255)
  • 创建一个可以从Android调用并提供对数据库访问权限的WCF服务,这可能是一个更好的解决方案,因为它也更安全。