使用JDBC连接的Andr​​oid到SQL Server [英] Connecting Android to SQL Server using JDBC

查看:300
本文介绍了使用JDBC连接的Andr​​oid到SQL Server的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为Android应用程序是应该同步它的数据MSSQL Server 2008中我目前正在测试出的方式,使其工作,因为我以前从来没有这样做。我应该指出,该设备将同步时,它连接到USB端口,而不是通过无线网络,因为该公司不希望在网络上注册的设备。

I am currently making an application for Android that is supposed to synchronize it's data to MSSQL Server 2008. I am currently testing out ways to make it work, since I have never done it before. I should mention that the device will sync whenever it is connected to the USB port and not through WiFi, since the company doesn't want to register the devices on the network.

到目前为止,这是我已经制定了到Java连接到SQL Server。这是一个简单的选择code(我目前使用的SQLEx preSS测试):

So far this is what I've worked out to connect Java to SQL Server. This is a simple Select code (I am currently using SQLExpress to test):

  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上的同样的事情,这就是它的样子:

Now, I've tried the same thing in Android and this is what it looks like:

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

在第一个例子中它完美的作品,但在第二个例子中它给了我这个错误:

In the first example it works perfectly, but in the second example it gives me this error:

12-17 20:15:12.589:E /错误(1668):   com.microsoft.sqlserver.jdbc.SQLServerException:该TCP / IP连接   到主机127.0.0.1,端口1433失败。错误:无法连接   到/127.0.0.1(1433端口)403ms后:isConnected失败:   ECONNREFUSED(连接被拒绝)。验证连接属性,   检查SQL Server的实例正在主机上运行,   接受TCP / IP连接的端口,并且没有防火墙   阻止TCP连接的端口。

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.".

我有这样的错误,我第一次遇到的第一个code,我只是不得不启用端口1433的SQL Server设置。我不明白,不过,为什么不工作的第二个表。这是相同的code,唯一的区别是,它通过一个按钮preSS执行,我有它在一个单独的线程运行。

I had that error the first time I ran the first code and I just had to enable port 1433 in the SQL Server Settings. I don't understand, though, why isn't it working on the second table. It is the same code, the only difference is that it's executed through a button press and that I have it running on a separate thread.

任何帮助将AP preciated,谢谢你。

Any help will be appreciated, thank you.

推荐答案

请参阅本节的模拟器Netorking

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

You need to use 10.0.2.2 which allows you to communicate from an emulator to the development machines 127.0.0.1 address.

您可能也不得不做一些端口重定向(另见该文档中)。

You may also have to do some port redirection (see further in that documentation).

这篇关于使用JDBC连接的Andr​​oid到SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆