我正在尝试从我的Android应用程序连接到mysql数据库。
我收到通讯链接失败错误。
以下是代码段:
public class MySqlConnector {
private Connection con = null;
private String s = "";
private String username = "root";
private String password = "password01";
private String connectionString;
public String ConnectToDb() {
connectionString ="jdbc:mysql://192.168.1.104:3306/mydatabase";
//connectionString="jdbc:mysql://10.0.0.0:3306/mydatabase";
// connectionString="jdbc:mysql://127.0.0.1:3306/mydatabase";
//connectionString = "jdbc:mysql://MainSrv04:3306/mydatabase";
// connectionString="jdbc:mysql://localhost:3306/mydatabase";
// connectionString =
// "jdbc:mysql://localhost:3306/mydatabase?user=root&password=password01&useUnicode=true&characterEncoding=UTF-8";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
con = DriverManager.getConnection(connectionString, username,
password);
Statement st = con.createStatement();
String sql = "SELECT First_Name FROM mydatabase.custinfo where CardNumber=5325784707";
ResultSet rs = st.executeQuery(sql);
s = rs.getString("First_Name");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
Log.i("MySqlConnector", "Database connection terminated");
} catch (Exception e) { /* ignore close errors */
}
}
}
if (s == "") {
s = "No Result";
}
Log.i("MySqlConnector : s=", s);
return s;
}
}
我尝试了所有可能的组合,如评论中所示,并在logcat中由字段导致中出现以下错误:
Caused by: java.net.ConnectException: localhost/127.0.0.1:3306 - Connection refused
Caused by: java.net.ConnectException: /127.0.0.1:3306 - Connection refused
Caused by: java.net.SocketException: The operation timed out
Caused by: java.net.SocketException: The operation timed out
Caused by: java.net.UnknownHostException: MainSrv04
我还通过 telnet 打了mysql
端口并且它正常工作。
另外,我已经处理了特权。
但我仍然遇到Communications link failure
错误。
任何帮助表示感谢。
答案 0 :(得分:2)
Android应用程序是否在同一个网络上?如果不是
jdbc:mysql://192.168.1.104:3306
和
JDBC:MySQL的://10.0.0.0:3306
无效。
提供正确的mysql网络地址。
答案 1 :(得分:1)
我使用最新版本的adt 和 mysql-connector-java-5.1.17-bin.jar ,这对我有用:
在行setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
并使用import android.os.StrictMode;
如果您使用新的API,请添加@SuppressLint("NewApi");