Heroku Postgres is not connecting - java

I have a working app on Heroku with which I can't manage to connect to the database allocated on Heroku
The method that gets the connection:
public static Connection connect() {
Connection conn = null;
try {
conn = DriverManager.getConnection(System.getenv("JDBC_DATABASE_URL"));
System.out.println("Connected to the PostgreSQL server successfully.");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
I check it with this other method on my API Rest:
#Path("/db")
#GET
public Response dbWorks() {
Connection conn = DBManager.connect();
if(conn != null) {
return Response.status(200).entity(conn).build();
}
return Response.status(400).entity(conn).build();
}
I does not work even if I write myself jdbc:postgresql://host:port/databasename with all the data that Heroku gives me.

Related

Why don't work on the device and work on the simulator?

I'm making an app that access a mysql DB. I'm using direct JDBC, not web service. The simulator access with no problem but the real device give the error
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
This is the code of the connection class (its only the connection method)
public static Connection CONN(String name) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL = null;
try {
Class.forName(classs);
conn = DriverManager.getConnection(url, un, password);
String stsql = "Select version()";
Toaster.toast(name);
//conn = DriverManager.getConnection(ConnURL);
} catch (SQLException se) {
Log.e("ERRO", se.getMessage());
Toaster.toast(se.getMessage());
System.out.println( se.getMessage() );
} catch (ClassNotFoundException e) {
Log.e("ERRO", e.getMessage());
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
Can someone gives me some help?
Thanks!

Could not get JDBC Connection; nested exception is java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection [duplicate]

Is it possible to do this in Java? Host in the connection string is unresolvable so I am getting SQLException in getConnection() of DataSource before I am able to call getMetaData on the connection.
This is my code:
DataSource ds = null;
Connection connection = null;
DataSourceProbeRequest request = null;
try {
request = (DataSourceProbeRequest) probeRequest;
ds = request.getDataSource();
connection = ds.getConnection();
final boolean validConnection = connection != null && connection.isValid(5000);
if (validConnection) {
LOGGER.info("Connection is ok: " + request.getTargetId());
return new ProbeResult(request.getTargetId(), buildDatasourceMsg(connection, true));
} else {
return new ProbeResult(request.getTargetId(), new Exception(buildDatasourceMsg(connection, false)));
}
} catch (Exception exp) {
return new ProbeResult(request.getTargetId(), exp);
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LOGGER.warn("Failed to close database connection", e);
}
}
}
Because the host is unreachable, connection = ds.getConnection(); would throw exception and causes new ProbeResult(request.getTargetId(), exp) returned. However, the exception only has error message like IO Error: The Network Adapter could not establish the connection. It doesn't give the host name in the connection string. I want to display the host name (or connection string) so that it can be diagnosed
It's a stupid error message from Oracle. Network adapters don't establish connections. TCP does. And, as you say, it suppresses all the important information.
But have a look further down the call stack, by chasing the detail chain from the original exception. Somewhere there should be a ConnectException with the message you want.

Mysql communication link failure despite can log on to the server from root

When i am trying to connect using the below function, it is showing "Communication link failure " from the application but not when i try login mysql directly. What can be the reason for this , and i am trying to access using root in the application.
public static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "12345");
} //end try
catch (Exception e) {
e.printStackTrace();
}
return con;
}

Unable to reopen MySQL connection in Java

I've got an annoying bug in Java. I'm connecting to a MySQL database and using Tomcat in Eclipse. It works brilliantly, but only the first time around. If I reload the page or run the page again, I get a com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
This is my code:
Connection conn = null;
String returnString = null;
Response response = null;
ResultSet rs = null;
try {
System.out.println("Trying to connect");
conn = DbUtil.getConnection(); // Connect to the database
System.out.println("Okay, connected");
query = conn.prepareStatement("SELECT host_firstname FROM host"); //Crashes at this line!
rs = query.executeQuery();
ConvertToJson jsonConverter = new ConvertToJson();
JSONArray jsonArray = new JSONArray();
jsonArray = jsonConverter.convertToJsonArray(rs);
returnString = jsonArray.toString();
response = Response.ok(returnString).build();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("hello!!!!");
}
finally {
if (rs != null){
rs.close();
}
if (query != null) {
query.close();
}
if (conn != null) {
conn.close();
}
}
return response;
I've seen everywhere I've Googled that I have to close the result set, the prepared statement and the connection (in that order) but once I've closed the connection, I can't reopen it.
This is my DbUtil class:
private static Connection connection = null;
public static Connection getConnection() {
if (connection != null) {
return connection;
}
else {
try {
Properties prop = new Properties();
InputStream inputStream = DbUtil.class.getClassLoader().getResourceAsStream("/db.properties");
prop.load(inputStream);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connection;
}
Any idea what is causing this problem?
Thanks
Omar :)
This answer is just to get your code working. But the best way would be to configure a connection pool. You should look about it.
YOur condition is :
if (connection != null) {
return connection; It's returning a closed connection
}
Try changing it to:
if (connection != null && !connection.isClosed()) {
return connection;
}

TCP/IP (Java Application to SQL Server)

I try to know if I can connect Java to SQL Server using these codes :
package pkgtry;
import java.sql.*;
public class NewMain {
public static void main(String[] args) {
String connectionUrl="jdbc:sqlserver://(local):1433;DatabaseName=OJT;user=sa;password=''";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
but on my end it show an error and says :
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection
to the host (local), port 1433 has failed. Error: "null. Verify the
connection properties, check that an instance of SQL Server is running
on the host and accepting TCP/IP connections at the port, and that no
firewall is blocking TCP connections to the port.".
What does it mean? How to fix it?
It means JDBC is unable to connect to the database server. It couldn't find the host (local), did you mean to put localhost here instead of (local)?
String connectionUrl="jdbc:sqlserver://(local):1433;DatabaseName=OJT;user=sa;password=''";
Do the following:
1)Make sure that the server is running on your computer . That is, its listening to incoming connection requests .
To do the above, use an IDE (I prefer netbeans....its very easy to use) and try creating a connection to the database. You will have to input username, password, databasename, the port no. on which the server is running and so on.
If you get a successful connection, your server is running fine.
If not, make sure you are using the correct driver, you have mentioned the right port number, right database name and so on.
2)Copy the connection string generated and replace it in the connection URL. I feel you should have a "localhost" instead of "(local)" in your connection string. But to be sure, just copy the connection string generated by your IDE.
3)Try connecting again and see if it works. It mostly should.
<%
String connectionUrl="jdbc:sqlserver://localhost:1433;DatabaseName=databaseNames;";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
out.println("<p>Driver not found:" + e + e.getMessage() + "</p>" );
}
try {
Connection conn = DriverManager.getConnection (connectionUrl, "sa", "yourPassword");

Categories

Resources