java - 使用 JDBC 将 Android 连接到 SQL Server

标签 java android sql-server jdbc

我目前正在为 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。不过,我不明白为什么它不能在第二张 table 上工作。这是相同的代码,唯一的区别是它是通过按下按钮执行的,而我让它在单独的线程上运行。

任何帮助将不胜感激,谢谢。

最佳答案

请参阅 Emulator Netorking 上的这一部分.

您需要使用 10.0.2.2,它允许您从模拟器与开发机器 127.0.0.1 地址进行通信。

您可能还需要进行一些端口重定向(请参阅该文档中的进一步内容)。

关于java - 使用 JDBC 将 Android 连接到 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13921546/

相关文章:

安卓。 CalendarView...一次只显示一个月的日历

sql - 比较 SQL 查询结果

sql - 如何计算SQL中2次之间的差异

sql-server - SQL Server 中的备份如何进行?

java - 如何计算上个月的天数?

java - Liferay 的带日期输入的自定义查询

java - 异常未传播到 Apache Camel 中的错误处理程序

php - ksoap2 响应为空。 responseDump 是 wsdl 文件本身,不是信封

java - 在一次调用中将 ArrayList.toString() 转换回 ArrayList

Java Android If Else Break 有问题故障排除