gpt4 book ai didi

java - 安卓 MySQL : JDBC CommunicationsException

转载 作者:行者123 更新时间:2023-11-29 08:03:31 27 4
gpt4 key购买 nike

我正在使用 Eclipse 和 Android 模拟器。我可以在模拟器浏览器中访问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();

}

}

最佳答案

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

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

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

check for more info

关于java - 安卓 MySQL : JDBC CommunicationsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23172484/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com