简体   繁体   中英

Connection to database failing for my mobile app on Android Studio

I am currently coding a mobile App and I need to gather some data from a database and display it on my mobile app. I installed MYSQL JDBC Connector and I set up the database with PhpMyAdmin. I have put the jar file (of the jdbc connector) in the libs directory and implemented it in the gradle scripts. I can connect to my database using the MySQL Workbench and even PhpMyAdmin, but I can't connect through the app.

You can see the error I get here. 错误

Here is a part of my code :

public class Tasks extends AppCompatActivity {
Connection connection;
private static final String url = "jdbc:mysql://127.0.0.1:3306/healthdb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT";
private static final String user = "root";
private static final String pass = "phantom";
private static final String query = "SELECT id FROM patient";
private Button doneBtn;
private Button nextBtn;
private ListView listView;
ArrayAdapter<String> adapter;
private Room room;
private TextView text;
String[] arrayTasks = {"Changing the sheets", "Blood test" , "Food distribution", "Physiological Constants"};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tasks);



    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        System.out.println("Connecting database...");
        connection = DriverManager.getConnection(url, user, pass);
        System.out.println("Connected");
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                // Retrieve by column name  
                System.out.print("ID: " + rs.getInt("id"));
            }
    }
    catch (SQLException | ClassNotFoundException se) {
        System.err.println(se);
    }

And here are my dependencies where you can see the jar file (I also moved the jar file into the libs directory) 执行

If you are running this on your mobile phone(through usb or wifi), the ip in the connection string doesn't work. You should go to your router settings enable port forwarding for port 3306, go to firewall enable port 3306 (inbound and outbound rules). Than you search what is my ip and replace 127.0.0.1 with your ip.(search for tutorial if you have problems with port forwarding) It should work.

You could also try getting the private network ip for your pc (you still have to enable inbound and outbound rules) and replace 127.0.0.0 with private ip of pc. This will work only if both devices are connected to the same router.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM