I have a class which connect to a MSSQL Database. The connection is successfully because if i run the code in my debugger (Eclipse) i can see that the connection is not null. Also the If-Statement is called because the connection is not null
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String query = "My Query";
con = DBVerbindung();
//The connection is not null
if (con != null) {
try {
//Here the connection is closed
stmt = con.prepareStatement(query);
} catch (Exception e) {
e.printStackTrace();
}
}
private Connection DBVerbindung() {
return DatabaseConnection.Verbindung();
}
}
But in the next line if i want to call the preparedStatement i got a Connection fail error:
Here is my DatabaseConnection Class
public class DatabaseConnection {
public static Connection Verbindung() {
final String connectionUrlMsSQLDEV = "jdbc:sqlserver://XXXXX:1234;databaseName=hrpap_itha_apps_dev;user=HRPAP-dev;password=XXXXX";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try (Connection conn = DriverManager.getConnection(connectionUrlMsSQLDEV)) {
if (conn != null) {
System.out.println("Verbunden!");
} else {
System.out.println("Fehler: Verbindung konnte nicht hergestellt werden! ---> " + DatabaseConnection.class.getName() );
}
return conn;
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
So why is the connection at this point null ?
Thanks

