0

I'm writing an Android application using Java and AndroidStudio as IDE; my application should communicate with the MySQL database that is hosted on a different machine than the one I'm launching my java code: the machine on which the MySQL server is running is an ubuntu machine, while the machine on which the java code is launched is a Windows machine (just to let you know). I'm using the java.sql.* library, so I create the connection with

Connection myConn = DriverManager.getConnection(url, username, password);

where username and password are the one that I insert to log in the database server, while the url parameter should be the url of my MySQL server; here is the problem: I don't know what I should write as url: the syntax should be

jdbc:mysql://<HOST_NAME>:<PORT>/<DB_NAME>

but apparently I don't know the HOST_NAME of my database because when I run the program the exception "Connection refused" is launched

I already have:

  • set MySQL connector/j as library in the project and specified the correct path for the .jar file
  • run the command sudo ufw allow mysql on the ubuntu machine
  • started the db

How can I connect to my database?

Ivan
  • 1
  • 1
  • 8
  • 1
    Use the IP address of the other machine or its domain name as "HOSTNAME". For example: `192.168.1.18` or `db.myserver.com`. – The Impaler Dec 20 '18 at 21:22
  • 1
    Just as a side note, directly connecting to a MySQL database from an Android app via jdbc is considered [very bad practice](https://stackoverflow.com/questions/26470117/can-we-connect-remote-mysql-database-in-android-using-jdbc) – Michael Dodd Dec 20 '18 at 21:26

3 Answers3

1

Use "ifconfig" in terminal of your Ubuntu to get the ip address. HOST_NAME : ip address of the database machine. PORT: 3306.

Eben
  • 19
  • 3
  • Hi Eben, thanks for the reply, but I was unable to solve the problem; I get these errors "CommunicationsException: Communications link failure", "The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server." Can you tell me what's the problem? – Ivan Dec 20 '18 at 23:31
0

Can you connect or login that mysql on computer B from computer A using terminal ? Did you grand privilege ,like this: grant all privileges on userDB.* to zs@localhost identified by '1234'

mingle08
  • 132
  • 2
  • Finally I made it: I had to edit the mysql.cnf file allowing connection from outside the localhost; thank you all for the replies! – Ivan Dec 21 '18 at 01:01
0

I did this many times. Login mysql using cmd on computer A, grant privilege to computer B, then B can connect mysql on A.

mingle08
  • 132
  • 2