简体   繁体   中英

Connect to remote MySQL server using Java

I'm writing a program to push stuff into a remote database. My database is stored on a redhat server, while my program is written on a windows machine.

I dont want to give out my server addresses but lets say my Linux server is xx.xx.xx.xx8

MySQL Workbench in windows says that my mysql server host is 127.0.0.1:3306

I know there are a million similar questions but each one is pretty unique to the situation.

I've been using http://www.vogella.com/tutorials/MySQLJava/article.html#javaconnection as a guide but this looks like a local connection.

I have also been referencing this but it confuses me.

Here's a mock up of some code i think may work:

Connection connection = null;
String dburl = "jdbc:mysql://127.0.0.1:3306/Db_Name";
String userName = "user";
String passWord = "password";



 try {
        Class.forName("com.mysql.jdbc.Driver");

        connection = DriverManager.getConnection(dburl, userName, passWord);
        Statement st = connection.createStatement();                                 

        String query = "INSERT INTO Example (`TestColumn`) VALUES('hello')";
        int rsI = st.executeUpdate(query);
        System.out.println("Hi");
        }catch (Exception e) {
        System.out.println(e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
                System.out.println("Database connection terminated");
            } catch (Exception e) { /* ignore close errors */ }
        }
    }

that is based on the link i provided. All i changed was the address. I have no idea where the server address xx.xx.xx.xx8 should go.

In order to connect to the remote database you need to know the external ( or called public ) ip address of the server.

String dburl = "jdbc:mysql://85.65.85.222:3306/Db_Name"

Even if your database on server says it listens on localhost:3306, you can still connect to it using public ip with correct port. (providing you have sufficient access rights to the server)

Sometimes there may be situation that even if you know the remote server IP address you still won't be able to connect to remote database directly perhaps due to blocked port or other ACL issues ( and this is ofc applicable if you have no control over this). You could however create ssh tunnel to that server and create a port forward.

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect(timeout);
session.setPortForwardingL(listenPort, destHost, destPort);

example ssh connnection could look something like this:

ssh user@85.65.85.222 -Llocalhost:5050:127.0.0.1:3306 <- this will create a ssh tunnel with port forwarding, meaning on your local machine where you have your code and whole environment you will still be able to connect to remote database using

String dburl = "jdbc:mysql://localhost:5050/dbname"

Just to clarify for anyone looking at this later...

localhost is always the machine you are sitting at - always. There is no way you will ever connect to a remote box using localhost. Also, the IP address 127.0.0.1 is equivalent to localhost, so don't use that either.

You may see that the database binds to localhost or 127.0.0.1 on the database server. That is ok. Use the IP address of the server running the database in your database connection URL

mysql:jdbc://<IPOfServer>:<PortOfServer>/<DbName>).

You can find the IP address of the server by running the following command on the database server...

Windows: ipconfig

Linux: ifconfig

Good luck!

You can see what documentation says:

The method DriverManager.getConnection establishes a database connection. This method requires a database URL, which varies depending on your DBMS. The following are some examples of database URLs:

MySQL: jdbc:mysql://localhost:3306/, where localhost is the name of the server hosting your database, and 3306 is the port number

So, for MySQL Connector/J Database URL

The following is the database connection URL syntax for MySQL Connector/J:

jdbc:mysql://[host][,failoverhost...] [:port]/[database] [?propertyName1][=propertyValue1] [&propertyName2][=propertyValue2]...

Where:

  • host:port is the host name and port number of the computer hosting your database. If not specified, the default values of host and port are 127.0.0.1 and 3306, respectively. So, every operation you do will be applied on this post

  • database is the name of the database to connect to. If not specified, a connection is made with no default database.

  • failover is the name of a standby database (MySQL Connector/J supports failover).
  • propertyName=propertyValue represents an optional, ampersand-separated list of properties. These attributes enable you to instruct MySQL Connector/J to perform various tasks.

Update : if you have a remote databases (your remote server) that you want to access to, you should have for example:

String dburl = "jdbc:mysql://<REMOTE_HOST>:3306/Db_Name"; //replace with your remote host 
... // here all the code related to your remote host

Note : if you remote server has in its configuration "localhost" you have to figure out its public ip address by executing ifconfig . Then use its ip address on your string. As important note your remote server must be configured to allow remote connections.

if you connect to a server (ie. with the ip xx.xx.xx.xx8) you specify through the port (which is usually 3306 ) that you want to connect to the databaseserver on that machine. so simply use:

String dburl = "jdbc:mysql://xx.xx.xx.xx8:3306/Db_Name";

as your connectionstring.

If you dont know the port, mysql is running, have a look in your /etc/mysql/my.cnf file. There should be the port specified.

Also have a look at your firewallrules if you can't connect and make sure you enabled remoteconnections (here is a good tutorial to enable it: http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html ).

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