0

Can anyone provide me the Java SE coding to connect to the MySQL database in a Server (not in the localhost)? what should I put instead of "localhost" and port number?

import java.sql.Connection;
import java.sql.DriverManager;

public class Main {
  public static void main(String[] argv) throws Exception {
    String driverName = "org.gjt.mm.mysql.Driver";
    Class.forName(driverName);

    String serverName = "localhost";
    String mydatabase = "mydatabase";
    String url = "jdbc:mysql :// " + serverName + "/" + mydatabase; 

    String username = "username";
    String password = "password";
    Connection connection = DriverManager.getConnection(url, username, password);
  }
}
5
  • What error do you get? If you are able to connect it on local computer then just replace localhost or your ip address in connection string with the ip address or domain name of remote computer where you want to connect. In your code replace localhost as a value of serverName with ip of remote machine. Also username/password you are using should be valid on remote machine's mySql Commented Aug 30, 2011 at 8:19
  • are there any coding to find the server ip address in java Commented Aug 30, 2011 at 8:21
  • 1
    Why do you need to find a server IP address? Are you not supposed to know that beforehand? Commented Aug 30, 2011 at 8:22
  • 2
    Your org.gjt.mm.mysql.Driver driver is obsolete, use the com.mysql.jdbc.Driver driver from now on. Also, just change your serverName to your server IP address. That's it! :-) Commented Aug 30, 2011 at 8:23
  • Thank you @The Elite Gentleman Commented Aug 30, 2011 at 8:36

1 Answer 1

5

simply use

String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

make sure that tou have access right to remote machine in mysql

give ip instead your.database.domain

Sign up to request clarification or add additional context in comments.

1 Comment

yes, but you need to change dburl and driver. i.e string in Class.forName

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.