Connect to MYSQL Databases hosted in a virtual machina from Java - java

I trying to conncet to my MySQL Database hosted in a virtual machine, but it doesn't work
for me.
Here is my setup:
Newest Ubuntu Server witch Apache2 mysql installed and is working
Database "feedback" with the table "test" set up and filled with test data
The network adapter is bridged. The IP of the server is (if I type in ifconfig) 10.0.0.1 and the IP of my pc is 10.0.0.4.
Port 3306 was manually opened. The jar mysql connector java 5.1.21-bin.jar is a Referenced Libary
Here is the Java Code:
import java.sql.*;
public class Main {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Sucess");
Connection con = DriverManager.getConnection("jdbc:mysql://10.0.0.1/feedback","root","myrootpassword");
con.setReadOnly(true);
} catch (Exception e) {
System.err.print("NO CONNECTION");
}
}
}
I hope that someone could help with this, because I'm working on this problem for a while.
Thanks

Just two ideas:
Is MySQL configured to listen on all addresses and not only local ones ? What's the value of the bind-address configuration directive ? 0.0.0.0 means "listen on all interfaces", while 127.0.0.1 means "listen on the localhost interface, for access from this host only".
Maybe you can extract some details about the issue in your catch statement ?
Hope this helps !

If i am correctly understand a question ,To connect VM database,then check for the following steps
1.jdbc:mysql://10.0.0.1/feedback.
2.Make sure there is no firewall blocking the access to port 3306.
3.make sure the user you are connecting with is allowed to connect from this particular hostname.

Related

Error 90 (Connection refused) when connecting to Remedy via Java

On my company network we run Remedy 7.64 and want to create Incidents automatically. I setup the development environment using IntelliJ IDEA and the ARAPI-files for my server version. We have no administration access to the server to change anything over there.
The error says
ERROR (90): Can't connect to AR System-Server; Connection refused:
connect <host>.
Mysteriously i can connect to the Web-Interface using Chrome, i can ping the host, i can access it via the Driver & the official Remedy Client and the java tool can get the source code of the web-interface of it as well, so it obviously is possible to connect to the host but the difficulty is somewhere else.
This is my simple demo file
import com.bmc.arsys.api.*;
public static void main(String [ ] args)
{
ARServerUser ctx = new ARServerUser();
ctx.setServer("<server>");
ctx.setUser("<user>");
ctx.setPassword("<pass>");
try {
ctx.login();
System.out.println("works");
} catch (ARException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
This is the list of dependancies
1.8 (java version "1.8.0_65")
[Module source ]
groovy-2.4.5
log4j-1.2.14.jar
arapi7604_build002.jar
You have to provide port number in which AR server is listening on. "ERROR (90): Can't connect to AR System-Server; Connection refused: connect ." means that the server refused to connect as you haven't mentioned the port number to connect. Normally people use 37000 as the AR server port number, but you have to check with your Remedy Admin to know this.
I just came across the same error. My issue was that I tried to connect using the full url as <server> ("https://..."). Using just the name of the server worked.

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).

SQLException: Communications link failure (Java/mysql)

Can someone explain to me why this line works:
conn = DriverManager.getConnection("jdbc:mysql://myWebsite.com:3306/schemaName?user=userX&password=passwordX");
But this line does not:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/schemaName?user=userX&password=passwordX");
I get a Communications Link Failure when attempting to access through the localhost (or 127.0.0.1). However, I'm able to access the database via localhost through PHP and the MySQLQuery Browser and MySQL Aministrator.
If needed here's the entire method I'm using:
public Database() throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
try {
conn = DriverManager.getConnection("jdbc:mysql://myWebsite.com:3306/schemaName?user=userX&password=passwordX");
// Next line does not work.
// conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/schemaName?user=userX&password=passwordX");
} catch (SQLException ex) {
displaySQLException(ex); // Seperate routine to display errors.
}
}
Thanks for any help,
Richard
It's possible your mysqld is binding specifically to the ethernet interface instead of all interfaces (0.0.0.0) or the localhost interface (127.0.0.1).
On a *nix platform you can check which interface the daemon is listening on with the following command:
$ netstat -ln|grep 3306
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
In second code:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/schemaName?
user=userX&password=passwordX");
It will try to connect to mysql on machine on localhost (on which the code is running). In your case it might be possible that mysql on your machine or from where you are running the code is not available or stopped or usename/password you are passing are not valid or schemaname does not exist. But on myWebsite.com it is up.
There is nothing wrong in your code. Make sure mySql is installed and running and username/password are valid, a schema with provided schemaname exists on machine on which you run this code with localhost.
This might happen for many reasons, like
MySQL server might be stopped on the target machine
MySQL might be configured not to accept remote connections
The firewall might be blocking remote connections on port 3306
In my case, I faced this error when trying to connect to mysql-server running inside a container on a Ubuntu host VM from the same host.
Example:
If my VM name is abc.company.com, the following jdbc URL would not work:
jdbc:mysql://abc.company.com:3306/dbname
Above jdbc url would work fine from other machines like xyz.company.com but just not abc.company.com.
where as the following jdbc URL would work just fine on abc.company.com machine:
jdbc:mysql://localhost:3306/dbname
which led me to check the /etc/hosts file.
Adding the following line to /etc/hosts fixed this issue:
127.0.1.1 abc.company.com abc
This seems to be an OS bug that requires us to add these on some Ubuntu versions.
Reference: https://www.debian.org/doc/manuals/debian-reference/ch05.en.html#_the_hostname_resolution
Before trying this, I had tried all other solutions like GRANT ALL.., changing the bind-address line in mysql.cnf.. None of them helped me in this case.

The Network Adapter could not establish the connection when connecting with Oracle DB

When trying to connect with a remote Oracle database via JDBC I receive the following exception:
java.sql.SQLRecoverableException: IO-fout: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:419)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:536)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:228)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
at java.sql.DriverManager.getConnection(DriverManager.java:322)
at java.sql.DriverManager.getConnection(DriverManager.java:358)
The following is my set-up:
Database: Oracle 10g Release 2 Standard Edition
JDBC library: ojdbc6.jar
JDBC driver: oracle.jdbc.driver.OracleDriver
JDBC URL: jdbc:oracle:thin:#9.2.2.2:1521:ORCL where ORCL is database's SID
JDBC User/pwd: Correct username / password
Strange about this problem is that the connection works just fine when I work from work. When I try to connect however from home via an AT&T VPN connection, it doesn't work.
I have confirmed that I can reach the IP address and have also telnetted the ip on port 1521, which works just fine. Connecting to the datasource from a local WebLogic Application Server also works alright. Furthermore, when trying to connect to the database via sqldeveloper I can also reach the database.
I need to reach the database however from a standalone application (for testing purposes). Does anyone have an idea why this problem occurs? And whether there are alternatives for connecting to a remote Oracle Database, alternatives which sqldeveloper and weblogic perhaps use?
Here's an excerpt of the code attempting to connect with the database:
public static void main(String args[]) throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#9.2.2.2:1521:ORCL", "user", "pwd");
}
When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.
So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.
If it is on a Linux box, I would suggest you add the database IP name and IP resolution to the /etc/hosts.
I have the same error and when we do the above, it works fine.
Take a look at this post on Java Ranch:
http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could
"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."
I had similar problem before. But this was resolved when I started using hostname instead of IP address in my connection string.

Connecting to hosted MySQL server with Java

I've been recently trying to connect to a hosted MySQL using Java but can't get it to work. I can connect to a local MySQL with localhost using:
connect = DriverManager.getConnection("jdbc:mysql://localhost/lego?"
+ "user=******&password=*******");
(Replacing the astrisks withmy username and password)
I can connect to the hosted MySQL database fine with PHP using:
mysql_connect('mysql.hosts.co.uk','******','**********');
mysql_select_db('test');
My problem is, I cannot connect via Java. I have an Exception which is caught if the connection doesn't work and this is always printed out.
Any ideas why it isn't working? Am I doing something wrong?
Thanks for your time,
InfinitiFizz
since it works in php (i guess you didn't try to connect from a local place with php???) it shouldn't be a port problem... but you should check that port 3306 is open... and ask the hosts company about that.
Have you noticed that in the DriverManager
http://java.sun.com/javase/6/docs/api/java/sql/DriverManager.html
you have:
getConnection(String url)
but also:
getConnection(String url, String user, String password)
Perhaps it would work better...
My guess is that you need to select a non-standard port, since I'd imagine the hosting server is serving lots of MySQL instances and they can't all use the normal one. I don't see selection of a port here.
If that's not it, perhaps there is a firewall issue somewhere along the way that's blocking the port or connection.

Categories

Resources