2012-12-17 2 views
3

현재 안드로이드 용 응용 프로그램을 만들었습니다.이 응용 프로그램은 데이터를 MSSQL Server 2008과 동기화해야합니다. 현재까지 사용하지 않았으므로 현재 작동 방법을 테스트 중입니다. 회사에서 네트워크에 장치를 등록하고 싶지 않기 때문에 장치가 USB 포트에 연결될 때마다 WiFi가 아닌 장치에 연결된다는 것을 언급해야합니다.JDBC를 사용하여 Android를 SQL Server에 연결

지금까지 내가 Java를 SQL Server에 연결하기 위해 노력한 내용입니다. 이것은 (I 현재 테스트 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) {} 
    } 

, 나는 안드로이드에 같은 일을 시도하고이는 모습입니다 :

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

에서 첫 번째 예는 완벽하게 작동하지만 두 번째 예에서 나에게이 오류 준다 : 나는 첫 번째 코드를 실행하고 난 그냥 SQL 서버 설정에서 포트 1433을 사용했다 처음

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

내가 그 오류를했다가 . 나는 이해하지 못한다. 왜 두 번째 테이블에서 작동하지 않는가? 그것은 동일한 코드입니다, 유일한 차이점은 버튼 프레스를 통해 실행된다는 것과 별도의 스레드에서 실행된다는 것입니다.

도움을 주시면 감사하겠습니다.

답변

4

Emulator Netorking을 참조하십시오.

에뮬레이터에서 개발 컴퓨터 127.0.0.1 주소로 통신 할 수있는 10.0.2.2를 사용해야합니다.

또한 포트 리디렉션을 수행해야 할 수도 있습니다 (자세한 내용은 해당 설명서 참조).

+0

+1. 이 대답은 내 대답보다 많은 정보를 가지고 있습니다. – kosa

관련 문제