使用JDBC将Android连接到SQL Server

3
我目前正在为Android开发一个应用程序,旨在将其数据同步到MSSQL Server 2008。我正在测试使其工作的方法,因为我以前从未这样做过。值得一提的是,设备将在连接到USB端口时进行同步,而不是通过WiFi进行同步,因为公司不想在网络上注册设备。
到目前为止,我已经解决了将Java连接到SQL Server的问题。以下是一个简单的Select代码(我目前正在使用SQLExpress进行测试):
  String connectionUrl = "jdbc:sqlserver://127.0.0.1:1433;" +
             "databaseName=Android;integratedSecurity=true;";

  // Declare the JDBC objects.
  Connection con = null;
  Statement stmt = null;
  ResultSet rs = null;

  try {
     // Establish the connection.
     Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
     con = DriverManager.getConnection(connectionUrl);

     // Create and execute an SQL statement that returns some data.
     String SQL = "SELECT * FROM AndroidTest;";
     stmt = con.createStatement();
     rs = stmt.executeQuery(SQL);

     // Iterate through the data in the result set and display it.
     while (rs.next()) {
        System.out.println(rs.getString(1) + " " + rs.getString(2));
     }
  }

  // Handle any errors that may have occurred.
  catch (Exception e) {
     e.printStackTrace();
  }
  finally {
     if (rs != null) try { rs.close(); } catch(Exception e) {}
     if (stmt != null) try { stmt.close(); } catch(Exception e) {}
     if (con != null) try { con.close(); } catch(Exception e) {}
  }

现在,我已经在Android上尝试了同样的事情,效果如下:

package com.example.testsqlserver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    public void clickSend(View view) {
        (new Thread(new TestThread())).start();
    }
    public class TestThread extends Thread {
      public void run() {
          String connectionUrl = "jdbc:sqlserver://127.0.0.1:1433;" +
                     "databaseName=Android;integratedSecurity=true;";

          // Declare the JDBC objects.
          Connection con = null;
          Statement stmt = null;

          try {
             // Establish the connection.
             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
             con = DriverManager.getConnection(connectionUrl);

             //Get information from EditText
             EditText txtTest = (EditText)findViewById(R.id.txtTest);
             EditText txtName = (EditText)findViewById(R.id.txtName);
             String test = txtTest.getText().toString();
             String name = txtName.getText().toString();

             // Create and execute an SQL statement that returns some data.
             String SQL = "INSERT INTO AndroidTest VALUES('" + test + "', '" + name + "');";
             stmt = con.createStatement();
             stmt.executeUpdate(SQL);
             Log.e("Success", "Success");
          }

          // Handle any errors that may have occurred.
          catch (Exception e) {
             e.printStackTrace();
              Log.e("Error", e.toString());
          }
          finally {
             if (stmt != null) try { stmt.close(); } catch(Exception e) {}
             if (con != null) try { con.close(); } catch(Exception e) {}
          }
      }

      public void main(String args[]) {
          (new TestThread()).start();
      }
    }
}

在第一个示例中,它能够完美地工作,但在第二个示例中,它给了我这个错误信息:
``` 12-17 20:15:12.589: E/Error(1668): com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host 127.0.0.1, port 1433 has failed. Error: "failed to connect to /127.0.0.1 (port 1433) after 403ms: isConnected failed: ECONNREFUSED (Connection refused). Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port."。 ```
我第一次运行第一个代码时也遇到了这个错误,我只需要在SQL Server设置中启用端口1433即可。但我不明白,为什么在第二个表格上它不起作用。这是相同的代码,唯一的区别是它通过按钮按下执行,并在单独的线程上运行。
任何帮助将不胜感激,谢谢。
1个回答

5

请参考模拟器网络这一章节。

您需要使用10.0.2.2地址,这可以让您从模拟器中与开发机器的127.0.0.1地址进行通信。

您可能还需要进行一些端口重定向(请参阅文档中的更多信息)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接