Jeong Ae Jeong Ae - 6 months ago 71
SQL Question

Using JDBC MySQL to connect database in Android?

I create an Android app to connect database using MySQL. When I test connection with localhost 10.0.2.2:3306, I can get database, but when I use the real host to get database from my server, I can not get anything. My host is: https://192.168.1.xxx:xxxxx and my database name is test. What is my problem? Please help me. Thank you.
This is my code:

private class MyTask extends AsyncTask<Void, Void, Void> {

private String idFromServer;
private String url="jdbc:mysql://192.168.1.xxx:xxxxx/test";
String name = "AAA";

@Override
protected Void doInBackground(Void... params) {
try {
ResultSet result = null;
String a = "SELECT * FROM testtable";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url,"aaa","abcdef");
Statement state = con.createStatement();
result = state.executeQuery(a);
while (result.next()) {
if (name.equals(result.getString("name"))) {
idFromServer = result.getString("id");
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(Void result) {
id.setText(idFromServer);
super.onPostExecute(result);
}

}

Answer

Generally MySql is installed with security restrictions so it is possible to access to it only from localhost.

You need to execute a command similar to the following to permit access from other ip

GRANT ALL PRIVILEGES
ON database.*
TO 'youruser'@'%'
IDENTIFIED BY 'yourpassword';

Note that it is a bad practice to offer access to MySql from any IP because it opens the possibility to be hacked. So generally it is a good idea to place a server that intercept requests from your android application and directly call the database.


Note: check also if it is open the route between your application and the mysql server.

If you use 3G you are not using a local network and the IP of the MySql server is different from 192.168.1.xxx (that is the ip of a local network). It is also possible that outside of the local network the MySql Server is not visible. It depends from the configuration of your network.

You need to "open" your network exposing the port to access mysql and checking which is the ip of your local network as seen from internet. Otherwise you can access to the local network using a phone with wireless connection to your local network.

Comments