Could not create connection to database server - java mysql connector - java

I can't connect to a mysql database on my "live-server" but it works just fine on my local computer.
In my main class I am doing this:
try {
main.connection.open();
} catch (SQLException e1) {
log.fatal(e1.getMessage());
System.exit(0);
}
And the open method looks like this
public void open() throws SQLException{
if(con != null) close();
con = DriverManager.getConnection(url, user, password);
}
After a couple of minutes running I am getting this:
14:35:47.434 [main] FATAL se.mypack.Server - Could not create connection to database server. Attempted reconnect 3 times. Giving up.
How do I debug this? The url, server and password variables is correct. What might be the problem here?
Using mysql-connector-java-5.1.29-bin.jar

First you have to make sure you have loaded your DB-driver class.
It goes as the following:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
This is for DERBY DB.
There is a different driver class for each DB, but the idea is the same.
If you already did it, check if you have a tcp connection to the DB server from the client machine
that tries to establish the connection. You can use : ping -t your.server.ip.
If you get a response, try to establish telet connection to that url + port number (the port that the DB listener listens to, for Oracle it will be 1521, for Derby it is 1527..) and see that you don't get any connection refuse messages.
If your connection attempt failed, see if the DB listener is up, or whether you have a fire wall issue.
Good Luck,
Yosi Lev

Related

JDBC DriverManager detect if the user is on the network before trying to connect to the database?

I'm working on a Java app that can be used connected to my office network or not.
My problem is that, when the user is not connected, the DriverManager.getConnection() takes up to 20 seconds before finally releasing that it can't connect to the database.
Code that connect me or not to the server :
public static Connection getConnection() {
try{
//cnx is my Connection object
if(cnx ==null || cnx.isClosed()){
Class.forName("com.mysql.jdbc.Driver");
//Get the connection if possible
cnx = DriverManager.getConnection(connectionString, user, password);
}
/*
Basically, I'm just checking if "ConfigUser.isConnected()" is true
later in the code to know if I should try to execute SQL queries
*/
ConfigUser.setConnected(true);
return cnx;
}
catch (Exception e){
}
ConfigUser.setConnected(false);
return null;
}
I've tried to use the DriverManager.setLoginTimeout() function but it didn't seem to change anything.
Add to connectionString connect timeout in milliseconds:
&connectTimeout=5000
connectTimeout
Timeout for socket connect (in milliseconds), with 0 being no timeout. Only works on JDK-1.4 or newer. Defaults to '0'.

SQLException while connecting to Azure SQL Data Warehouse using JDBC

I am trying to connect to Azure SQL Data Warehouse through JDBC. I am getting the following exception.
*
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host tcsqldatawh.database.windows.net, port 1433 has failed. Error: "null. 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.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:242)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2280)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:493)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1387)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1068)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:904)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:451)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1014)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at testsqldw.SQLDatabaseConnection.main(SQLDatabaseConnection.java:30)
*
I have seen similar questions asked about connecting to the SQLServer DB here.
I configured the database to allow access to my IP using the process here.
Please check the code below:
package testsqldw;
import java.sql.*;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionString =
"jdbc:sqlserver://databaseserver.database.windows.net:1433;"
+"database=databaseserver;"
+"user=username#databaseserver;"
+ "password=password;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "hostNameInCertificate=*.database.windows.net;"
+ "loginTimeout=30;";
System.out.println("Total connection string is---\n"+connectionString);
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String createSql = "create table employee(employee_id varchar(20));";
statement = connection.createStatement();
boolean status=statement.execute(createSql);
System.out.println(status);
// Print results from select statement
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the connections after the data has been handled.
if (statement != null) try { statement.close(); } catch(Exception e) {}
if (connection != null) try { connection.close(); } catch(Exception e) {}
}
}
}
Total connection string is
jdbc:sqlserver://databaseserver.database.windows.net:1433;database=databaseserver;user=username#databaseserver;password=password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
Please help me in resolving the issue.
Per my experience, the issue may be caused by the following reasons:
The SQL Server which you have created may not work fine.
You may use incorrect JDBC connection string.
For the first reason, you could use some client tools to connect to the SQL server. If you could connect to the server, that indicates the SQL server is ok.
If not ,you could create a new SQL Server. After then, you could create a new SQL Data Warehouse according to this URL https://azure.microsoft.com/en-us/documentation/articles/sql-data-warehouse-get-started-provision/.
The URL also includes the firewall config method.
I use the SQL Server InTouch to connect to the SQL Server. The followings are some description images.
You could get the parameters by the Azure Portal. The port number is 1433.
The following picture indicates that your server is ok.
For the second reason, you could copy the connection string from the azure portal and modify the password only.
Hope it helps. Any concerns, please feel free to let me know.

Connect to mysql remote database using JDBC?

I'm a java beginner and I'm working on a simple application which connects to a remote mysql database using JDBC. I've tested it locally and it works just fine, however I cannot get it to work on for my remote server.
I don't think its of much use but heres the code:
Connection connection = null;
String dburl = "jdbc:mysql://314159265: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 */ }
}
}
When I run this, I get the following message:
com.mysql.jdbc.exceptions.jdbc4.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.
I'm pretty sure it must be some kind of server configuration issue.
Notes:
Username, password, IP, database name, etc. are just examples.
This could be a firewall problem, or a configuration problem. But I don't think it is a coding problem at all - you need to start troubleshooting the connection.
Trouble shoot by attempting to use third party client apps to connect to mysql. This will indicate whether it is configured for external access. Although it doesn't ensure that JDBC is visible from the outside, it does rule out some potential firewall problems.
Follow this guide to help you mess with your configurations
Remote MYSQL Database Access
If you are still stuck, it could be a coding problem so check out this page:
How to connent to a remote mysql database with java?
P.S. I am assuming you are using unix as the operating system.
I guess 314159265 could be replaced by some address....
like jdbc:mysql://localhost:3306/
or jdbc:mysql://127.0.0.1:3306/

Unable to get a SQL-Server connection

Im having difficulties trying to get a connection to my sqlserver database.
The database im using is SQL-Server 2008.
The driver im using is the one i got here: Microsoft download page
I use the following code:
public static final String URL_FORMAT = "jdbc:sqlserver://%s:%s;DatabaseName=%s";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
String connectionURL = String.format(URL_FORMAT, "10.31.3.3", 1433, "EPowerTest");
System.out.println("connecting to: "+connectionURL);
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection(connectionURL, "sa", "*************");
if (connection == null) {
System.out.println("no connection was established");
} else {
System.out.println("succesfully connected");
}
}
Now this piece of code runs on my developers machine, im getting the following results:
connecting to: jdbc:sqlserver://...:1433;DatabaseName=******
succesfully connected
But when i run this piece of code on my developers machine it prints the follwing:
connecting to: jdbc:sqlserver://10.31.3.3:1433;DatabaseName=*******
and the second line never gets printed, because it seems DriverManager.getConnection does not return. This is not a firewall issue, since all three terminals (db server, developers machine and the test machine) are all on the same network. Why is my method not returning? am i missing some important SQLServer files?
Hope anyone here can help me with this annoying problem!
Check if the JVM in the machine that the connections hangs is the version 1.6.0_29. If it is, upgrade to a newer Java.
Here is another link explaining the issue.

JDBC Example for java

I have downloaded JDK 6 and also I have sqljdb4.jar and I have database.properties file that content the following data
database.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
database.url=jdbc:sqlserver://.;databaseName=UserInfo;integratedSecurity=true;
database.username=sa
database.password=admin
B.N : I'm installing the server on my machine and the server name = . , also I'm using Windows Authontication
My problem now is when I try to create connection I have the following error
com.microsoft.sqlserver.jdbc.SQLServerException:
The TCP/IP connection to the host
localhost, port 1433 has failed.
Error: Connection refused: connect.
Please verify the connection
properties and check that a SQL Server
instance is running on the host and
accepting TCP/IP connections at the
port, and that no firewall is blocking
TCP connections to the port. at
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:130)
I don't know what is the exact problem here
If any one can help I will be appreciated
Thanks in Advance
That's caused by many probabilities like
1- IP is worong
2- Port is wrong
3- There is firewall prevent machine to go out and connect to another IP
4- SQL server down .
try to use
public class JdbcSQLServerDriverUrlExample
{
public static void main(String[] args)
{
Connection connection = null;
try
{
// the sql server driver string
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// the sql server url
String url = "jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE";
// get the sql server database connection
connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
// now do whatever you want to do with the connection
// ...
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}
}
}
What i need to explain is there is very good technology called " Persistence " is better than JDBC and is more than brilliant and easy to use .
The problem is that your SQL server is either
not installed,
not running or
not accepting TCP/IP connections.
Particularly the last one is nasty, as I remember that some versions of SQL Server have not configured the TCP/IP connector to run by default.
Well first and foremost we need to see your code. Second looking at the error message the database is A)not running
B) on a different port
or C) the code is incorrect.

Categories