Class.forName("oracle.jdbc.driver.OracleDriver"); throwing NullPointerException - java

Class.forName("oracle.jdbc.driver.OracleDriver");
is throwing NullPointerException, I have tried a lot to solve it but failed.
You can check following function where the problem is occuring:
public static Connection con=null;
public static Connection getOracleConnection()
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe",Constants.OracleUsername,Constants.OraclePassword);
}catch(NullPointerException npe){ npe.printStackTrace(); }
catch(Exception e){ System.out.println("Error to create the connection "); }
return con;
}

Check that the Oracle JDBC driver is in your classpath.
You can find one on the page below if not yet downloaded:
http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html

Related

Unable to connect database to server [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 11 days ago.
Unable to connect Postgres database to Tomcat 10.0.27 server
Here is DBConnection code:
public class DBConnection {
public static Connection getConnectionToDatabase() {
Connection connection = null;
try {
System.out.println("MySQL JDBC Driver Registered!");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/hplus", "postgres", "");
}
catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
System.out.println("Connection made to DB!");
}
return connection;
}
}
Here is the code, where i try to get the connection:
public class ApplicationDao {
public List<Product> searchProducts(String searchString) {
Product product = null;
List<Product> products = new ArrayList<>();
try{
Connection connection = DBConnection.getConnectionToDatabase();
String sql = "select * from products where product_name like '%"+searchString+"%'";
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(sql);
while(set.next()){
product= new Product();
product.setProductId(set.getInt("product_id"));
product.setProductImgPath(set.getString("image_path"));
product.setProductName(set.getString("product_name"));
products.add(product);
}
}
catch(SQLException exception){
exception.printStackTrace();
}
return products;
}
}
Here is what i get:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Cannot invoke "java.sql.Connection.createStatement()" because "connection" is null
I tried to debug the code but got no response. I looked on different forms what the problem is, but I did not find anything
The problem was in incorrect driver. Everything work out after adding this lines of code in DBConnection class:
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// ...

The value of the local variable conn is not used

As I mentioned on the subject, I am facing the warning "The value of the local variable conn is not used"
I clearly used the variable on my coding but it shows me that type of error.
It will be highly appreciated if you can advise me on this.
[CODE]
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class example {
public static void main(String[] ar) {
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Success to find Driver");
}catch(ClassNotFoundException e) {
System.err.println("error = Failed to find driver");
}//*Find MYSQL driver
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/class", "root", "****");
System.out.println("Connected to MySql");
} catch (SQLException e) {
System.err.println("error = Failed to Create connection");
}//* Creating Connection
}
}
[RESULT AFTER RUN]
Success to find Driver
error = Failed to Create connection
In your code you have assigned a reference to conn but you are not using that object anywhere, hence the warning.
To get rid of the warning either use it somewhere (maybe do a sysout somewhere) or add the #SuppressWarnings("unused") annotation

Java switch connection when connection error occured (Failover connection)

Is it possible switch to second connection source with JAVA when sql connection error occured ?
protected Connection dbConnect(String jdbcProvider) throws
MbException,SQLException{
return getJDBCType4Connection(jdbcProvider,JDBC_TransactionType.MB_TRANSACTION_AUTO);
}
protected Connection dbStandByConnect(String jdbcProvider,String jdbcProvider2) throws MbException{
Connection con=null;
try {
con= dbConnect(jdbcProvider);
} catch (SQLException e) {
try {
con= dbConnect(jdbcProvider2);
} catch (SQLException sqlEx) {
throw new RuntimeException(sqlEx);
}
}
return con;
}
I have no idea if it is right way or not ? Do you have any suggestions as to how I can make this work?
Thanks in advance.

java web app refuses to connect to SQL Database when deployed on Tomcat

So i am facing the following problem.
I have developed an web app that has the following connection to a SQL Server database. (db connection code attached)
public class DBConnection
{
private DatabaseMetaData dma;
private static Connection con;
private static DBConnection instance = null;
private static String security = "integratedSecurity=true;";
private DBConnection()
{
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} catch (Exception e) {
System.out.println("Can not find the driver");
System.out.println(e.getMessage());
}
try{
con = DriverManager.getConnection("jdbc:jtds:sqlserver://<Machine>;databaseName=<DBName>; useNTLMv2=true;");
//set autocommit
con.setAutoCommit(true);
dma = con.getMetaData(); // get meta data
System.out.println("Connection to " + dma.getURL());
System.out.println("Driver " + dma.getDriverName());
System.out.println("Database product name " + dma.getDatabaseProductName());
}
catch(Exception e){
System.out.println("Problems with the connection to the database");
System.out.println(e.getMessage());
System.out.println(con);
}
}
public static void closeConnection()
{
try{
con.close();
System.out.println("The connection is closed");
}
catch (Exception e){
System.out.println("Error trying to close the database " + e.getMessage());
}
}
public Connection getDBcon()
{
return con;
}
public static DBConnection getInstance()
{
if (instance == null)
{
instance = new DBConnection();
}
return instance;
}
public static void startTransaction()
{ try{
con.setAutoCommit(false);
}
catch(Exception e){
System.out.println("fail start transaction");
System.out.println(e.getMessage());
}
}
public static void commitTransaction()
{ try{
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail commit transaction");
System.out.println(e.getMessage());
}
}
public static void rollbackTransaction()
{
try
{
con.rollback();
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail rollback transaction");
System.out.println(e.getMessage());
}
}
I am using a Tomcat 8 on InteliJ IDE for running the app and debugging. Which works fine. (DB connection is established)
The problem is that when i take the war file and deploy it in the same Tomcat Server i get no DB Connection. (No DB connection)
I have checked all the .jar files in the tomcat and the project and I have added all the needed files.
Can't seem to find what is causing this issue. Maybe there is someone who got stuck with the same issue
I can't get a proper undertanding what is causing this issue and how to fix it
**EDIT: Following I have added the error displayed when trying to load data
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is java.lang.NullPointerException
root cause
java.lang.NullPointerException
com.lifeletapp.business.dataLayer.DbLogIn.isValidUser(DbLogIn.java:27)
com.lifeletapp.business.HelloController.verifyLogin(HelloController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
DbLogin class:
public class DbLogIn implements ILogIn
{
private Connection conn;
public DbLogIn()
{
conn = DBConnection.getInstance().getDBcon();
}
public Staff isValidUser(String userName, String password)
{
Staff staff = new Staff();
try {
String query = "SELECT * FROM Staff WHERE userName=? AND pass=?";
PreparedStatement preparedStatement = conn.prepareStatement( query );
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
while( resultSet.next() ) {
staff.setUserID(resultSet.getInt("userID"));
staff.setfName(resultSet.getString("fName") );
staff.setlName(resultSet.getString("lName") );
staff.setUserName(resultSet.getString("userName") );
staff.setPass(resultSet.getString("pass") );
staff.setEmail(resultSet.getString("email") );
}
resultSet.close();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return staff;
}
}
This is more a config or server issue. Not a code issue.
As mentioned in the comments I have tested if var conn == null -> resulted true. And the connection dose not get nulled anywhere. Please view code. Then again the above code works when run from the InteliJ debugger.
So finally figured out what was the issue.
Why was it working on my IDE config:
1. I was using java JDK 1.7 as JAVA_HOME
2. I was using an older version of Tomcat as a build
3. In order to work with JDTS you need to extract the nlmauth.dll from the .jar archive and copy it to the configured env JDK(jdk1.7-->>bin->>copy here)
Why was it not working on Tomcat server:
1.I was using Tomcat 8.xxx
2.Tomcat 8.xx require JDk 8
3. In the JDK 8 i have not past the nlmauth.dll ( once i have done this everything was working)
In order to approach this issue the first clue will be looking into the tomcat server logs.
On my presumption this issue is prom to occur only when you have an Database connection establish via Integrated Security.
My presumption is related to the fact that in the tomcat log the main error that was denying the JDBC driver was based on the integrated security credentials.
Best of luck to you all out there.

No suitable Driver error

public void connect()
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:msql://23.249.225.135:3306/";
Connection conn = DriverManager.getConnection(url,"s****d","1*****-");
System.out.println("DB works");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
I have the JDBC driver in the /lib folder in my class path.
Keep getting:
No suitable driver found for jdbc:msql://23.249.225.135:3306/
Any ideas?
You've misspelled mysql in the url is msql.
The version of your mysql database doesn't support the version of your driver or vice-versa.
Look for the compatibility matrix here: Chapter 2 Connector/J Versions

Categories