在android模拟器中使用远程系统的IP地址连接远程mysql数据库

时间:2012-02-07 05:17:24

标签: java android eclipse

这是以下代码:

 `package com.tom.jam;

//import java.sql.Connection;
//import java.sql.DriverManager;
 import java.sql.*;
import android.app.Activity;
//import android.database.SQLException;
import android.os.Bundle;
import android.widget.TextView;

 public class MyserverActivity extends Activity {
TextView mf,ct;
  /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mf=(TextView) findViewById(R.id.myfield);
    ct=(TextView) findViewById(R.id.cont);
        Connection con = null;

        try {
          Class.forName("com.mysql.jdbc.Driver");
          con=DriverManager.getConnection("jdbc:mysql://192.168.0.100/test","root", "secret");
          if(!con.isClosed())
          {

              Statement st = con.createStatement();
              ResultSet rs = st.executeQuery("select * from ram");
              while(rs.next())
              {
              ct.setText("ID" + rs.getString(1) + "Name " + rs.getString(2));
              }

            mf.setText("Successfully connected to " +
              "MySQL server using TCP/IP...");

          }
        } catch(Exception e) {
          mf.setText("Exception: " + e.getMessage());
        } finally {
          try {
            if(con != null)
              con.close();
          }catch (java.sql.SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}
}
}`   

我们在

中设置了以下权限
manifest:android.permission.ACCESS_NETWORK_STATE,
         android.permission.INTERNET,
         android.permission.WRITE_EXTERNAL_STORAGE       

没有错误和警告,但在运行模拟器时显示以下异常:

 Unable to connect to any hosts due to exception:java.net.SocketTimeoutException:Connection timed out.

提前致谢

1 个答案:

答案 0 :(得分:0)

java.net.SocketTimeoutException:连接超时,当目标系统不可访问时发生异常。这可能是由于代理未在您的模拟器上设置,要在模拟器上设置代理,您可以在命令提示符中通过命令启动模拟器:

emulator -avd avdname -http-proxy http://192.168.1.1:8080

此处将avdname替换为您要运行程序的avd名称,并将http:192.168.1.1替换为您的代理服务器。