Couldn't connect to a MySQL DB via JWS app - java

Could someone help me with establishing connection with my DB on non-localhost server?
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://"+SERVER+"/javadb?user=javadb&password=*****");
How could I set-up the SERVER String for my domain www.lmntstudio.cz?
All required files are stored in one folder on the server.
I did it first on my localhost server and everything works well. But with the connection to another server is trouble.

I would recommend not to open MySQL connection from the client/user machine to the server. Because this would make your DB server open and prone to attacks.
Rather consider using web service. call that web service from your JWS application from client side and get the data.
Another point to consider is that opening a connection on a port say 3360 may be blocked by the firewall. If my firewall is set to block any out bound connection on port 3306 the connection could not be established.

Please ensure the MySQL is running in default port 3306 else you need change the port number accordingly.
Connection connection = DriverManager.getConnection(
"jdbc:mysql://www.lmntstudio.cz:3306/javadb", "username", "password");
instead of www.lmntstudio.cz you can use ip of the domain.
run the following in the command line to get the ip
cmd prompt> nslookup www.lmntstudio.cz
The Url syntax as follows
jdbc:mysql://(host/ip):port/databasename", "username", "password"

Related

Java web app can't connect to sql server [duplicate]

I want to connect Java class file with SQL server 2012. I have logged in with SQL server authentication, but I am receiving an error when connecting.
Error:
The TCP/IP connection to the host 127.0.0.1, port 1433 has failed.
Error: "Connection refused: connect. Verify the connection properties.
Make sure that an instance of SQL Server is running on the host and
accepting TCP/IP connections at the port. Make sure that TCP
connections to the port are not blocked by a firewall.".
My code:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //1. Register your driver
//2. get the connection object
//Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=aysha","sa","admin");
Connection con = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1;databaseName=aysha","user=sa","password=admin");
//"jdbc:sqlserver://127.0.0.1:1433; Instance=SQL2008;" + "databaseName=MB;user=sa;password=123;";
//Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=aysha","sa" , "password");
//3. Prepare a statement
Statement stmt = con.createStatement();
//4. Write the query`
String sql = "Select * from employee";
//5. Execute the statement and
ResultSet rs = stmt.executeQuery(sql);
//6. Process the result set
while (rs.next())
{
System.out.println(rs.getInt(1));
}
Open SQL Server Configuration Manager, and then expand SQL Server 2012 Network Configuration.
Click Protocols for InstanceName, and then make sure TCP/IP is enabled in the right panel and double-click TCP/IP.
On the Protocol tab, notice the value of the Listen All item.
Click the IP Addresses tab:
If the value of Listen All is yes, the TCP/IP port number for this instance of SQL Server 2012 is the value of the TCP Dynamic Ports item under IPAll.
If the value of Listen All is no, the TCP/IP port number for this instance of SQL Server 2012 is the value of the TCP Dynamic Ports item for a specific IP address.
Make sure the TCP Port is 1433.
Click OK.
Easy Solution
Got to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager ->Expand SQL Server Network Configuration-> Protocol ->Enable TCP/IP Right box
Double Click on TCP/IP and go to IP Adresses Tap and Put port 1433 under TCP port.
The error is self explanatory:
Check if your SQL server is actually up and running
Check SQL server hostname, username and password is correct
Check there's no firewall rule blocking TCP connection to port 1433
Check the host is actually reachable
A good check I often use is to use telnet, eg on a windows command prompt run:
telnet 127.0.0.1 1433
If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem
Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager.
If you see that SQL Server/ SQL Server Browser State is 'stopped'.Right click on SQL Server/SQL Server Browser and click start.
In some cases above state can stop though TCP connection to port 1433 is assigned.
Open %windir%\System32 folder and find SQLServerManagerXX.msc
For example:
C:\Windows\System32\SQLServerManager14.msc
Go to protocols settings then enable TCP/IP port is 1433 by default
As the error says, you need to make sure that your sql server is running and listening on port 1433. If server is running then you need to check whether there is some firewall rule rejecting the connection on port 1433.
Here are the commands that can be useful to troubleshoot:
Use netstat -a to check whether sql server is listening on the desired port
As gerrytan mentioned in answer, you can try to do the telnet on the host and port
important:
after any changes or new settings you must restart SQLSERVER service. run services.msc on Windows
If you are using a named instance, the port you using likely is 1434, instead of 1433, so please check that out using telnet or netstat aforementioned too.
Open Firewall GUI,Open TCP 1433 rule,go to scope tab and add your IP address under Remote IP Address and the problem is solved.

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

JDBC connection failed, error: TCP/IP connection to host failed

I want to connect Java class file with SQL server 2012. I have logged in with SQL server authentication, but I am receiving an error when connecting.
Error:
The TCP/IP connection to the host 127.0.0.1, port 1433 has failed.
Error: "Connection refused: connect. Verify the connection properties.
Make sure that an instance of SQL Server is running on the host and
accepting TCP/IP connections at the port. Make sure that TCP
connections to the port are not blocked by a firewall.".
My code:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //1. Register your driver
//2. get the connection object
//Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=aysha","sa","admin");
Connection con = DriverManager.getConnection("jdbc:sqlserver://127.0.0.1;databaseName=aysha","user=sa","password=admin");
//"jdbc:sqlserver://127.0.0.1:1433; Instance=SQL2008;" + "databaseName=MB;user=sa;password=123;";
//Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=aysha","sa" , "password");
//3. Prepare a statement
Statement stmt = con.createStatement();
//4. Write the query`
String sql = "Select * from employee";
//5. Execute the statement and
ResultSet rs = stmt.executeQuery(sql);
//6. Process the result set
while (rs.next())
{
System.out.println(rs.getInt(1));
}
Open SQL Server Configuration Manager, and then expand SQL Server 2012 Network Configuration.
Click Protocols for InstanceName, and then make sure TCP/IP is enabled in the right panel and double-click TCP/IP.
On the Protocol tab, notice the value of the Listen All item.
Click the IP Addresses tab:
If the value of Listen All is yes, the TCP/IP port number for this instance of SQL Server 2012 is the value of the TCP Dynamic Ports item under IPAll.
If the value of Listen All is no, the TCP/IP port number for this instance of SQL Server 2012 is the value of the TCP Dynamic Ports item for a specific IP address.
Make sure the TCP Port is 1433.
Click OK.
Easy Solution
Got to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager ->Expand SQL Server Network Configuration-> Protocol ->Enable TCP/IP Right box
Double Click on TCP/IP and go to IP Adresses Tap and Put port 1433 under TCP port.
The error is self explanatory:
Check if your SQL server is actually up and running
Check SQL server hostname, username and password is correct
Check there's no firewall rule blocking TCP connection to port 1433
Check the host is actually reachable
A good check I often use is to use telnet, eg on a windows command prompt run:
telnet 127.0.0.1 1433
If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem
Go to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager.
If you see that SQL Server/ SQL Server Browser State is 'stopped'.Right click on SQL Server/SQL Server Browser and click start.
In some cases above state can stop though TCP connection to port 1433 is assigned.
Open %windir%\System32 folder and find SQLServerManagerXX.msc
For example:
C:\Windows\System32\SQLServerManager14.msc
Go to protocols settings then enable TCP/IP port is 1433 by default
As the error says, you need to make sure that your sql server is running and listening on port 1433. If server is running then you need to check whether there is some firewall rule rejecting the connection on port 1433.
Here are the commands that can be useful to troubleshoot:
Use netstat -a to check whether sql server is listening on the desired port
As gerrytan mentioned in answer, you can try to do the telnet on the host and port
important:
after any changes or new settings you must restart SQLSERVER service. run services.msc on Windows
If you are using a named instance, the port you using likely is 1434, instead of 1433, so please check that out using telnet or netstat aforementioned too.
Open Firewall GUI,Open TCP 1433 rule,go to scope tab and add your IP address under Remote IP Address and the problem is solved.

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 external database through telnet

I have a java program that connects to a MS SQL database. The program works perfectly when running through eclipse however I get an error when I run it through AIX:
java.sql.SQLException: Network error IOException: A remote host refused an attempted connect operation.
I can successfully ping the server but am not able to telnet into the server. I am also not able to telnet from my windows desktop.
I am using jtds to connect:
String connectionString = "jdbc:jtds:sqlserver://"+dropez_ip_address+"/"+dropez_db_name;
ResultSet rs = null;
Statement stmt = null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(connectionString, dropez_db_username, dropez_db_password);
stmt = conn.createStatement();
}catch(Exception e){}
Here is some documentation from jTDS regarding the issue, but I am still not able to resolve the issue.
Why do I get java.sql.SQLException: "Network error IOException: Connection refused: connect" when trying to get a connection?
The "Connection refused" exception is thrown by jTDS when it is unable to connect to the server. There may be a number of reasons why this could happen:
- The server name is misspelled or the port number is incorrect.
- SQL Server is not configured to use TCP/IP. Either enable TCP/IP from SQL Server's Network Utility app or have jTDS connect via named pipes (see the URL format for information on how to do this).
- There is a firewall blocking port 1433 on the server.
To check whether TCP/IP is enabled and the port is not blocked you can use "telnet 1433". Until telnet doesn't connect, jTDS won't either. If you can't figure out why, ask your network administrator for help.
If you can't telnet on port 1433, you are blocked by a firewall somewhere in the middle between your machine and the server. That's not a java related problem.
May it be that when you say "it runs perfectly under eclipse but not AIX" you are taking about 2 different computers ? If so, the one with eclipse is not firewalled, the one where you deploy your app is blocked.
But again, nothing to do with java. It's a level 3 error (TCP layer) of TCP-IP model.
Regards,
Stéphane
Your SQL Server database probably doesn't have the TCP/IP protocol enabled, to enable it:
From the Microsoft SQL Server 2005 -> Configuration Tools, open the 'Microsoft SQL Server Configuration Manager'.
Expand ‘SQL Server 2005 Network Configuration’, and then click ‘Protocols for ’.
Right-click ‘TCP/IP’ and then click ‘Enable’. The icon for the protocol will change to show that the protocol is enabled.
For SQL Server 2008:

Categories

Resources