Android MySql:JDBC CommunicationsException

时间:2014-04-19 16:24:12

标签: java android mysql jdbc

我正在使用Eclipse和Android Emulator。我可以在模拟器浏览器中访问10.0.2.2。但在我的应用程序中,此代码无法运行:

Connection con = DriverManager.getConnection("jdbc:mysql://10.0.2.2/stu", "user", "pass");

有人有想法吗?

错误是:

com.mysql.jdbc.CommunicationsException

我很困惑,为什么我可以在模拟器的浏览器中访问phpMyAdmin,但不在代码内部! :(

注意完整代码是这样的:

public class LearningActivity extends Activity {

private static final String url = "jdbc:mysql://10.0.2.2/stu";
private static final String user = "root";
private static final String pass = "11111";
private Button button;
private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    button = (Button)this.findViewById(R.id.button1);
    tv = (TextView)this.findViewById(R.id.textView1);

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            Connect();
        }
    });
}


private class Connect extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response = "";

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(url, user, pass);
            // System.out.println("Database connection success");

            String result = "Database connection success\n";
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select * from users");
            ResultSetMetaData rsmd = rs.getMetaData();

            while(rs.next()) {
                result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
                result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
                result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
            }
            tv.setText(result);
        }
        catch(Exception e) {
            e.printStackTrace();
            tv.setText(e.toString());
        }
        return response;   


    }

    @Override
    protected void onPostExecute(String result) {
        tv.setText(result);
    }
}

public void Connect() {
    Connect task = new Connect();
    task.execute();

}

}

3 个答案:

答案 0 :(得分:1)

您的mysql数据库应该可以从远程系统访问。

您应该授予远程访问权限  像这样的东西

GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.%'
    IDENTIFIED BY PASSWORD 'password'  
    WITH GRANT OPTION;
FLUSH PRIVILEGES;

check for more info

答案 1 :(得分:1)

该死的!我错过了添加Internet权限清单! :( 我补充说,问题解决了。

手机浏览器(android模拟器)拥有此权限,可以连接到网络,但我的应用程序没有该权限。所以我应该只将这一行添加到manifest.xml:

<manifest ... >
.
.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
.
.
</manifest>

答案 2 :(得分:0)

你没有改变ip ...... 1&gt;让你的机器ip 2&gt;然后Connection con = DriverManager.getConnection(“jdbc:mysql://”你的ip“/ stu”,“user”,“pass”);