I'm working on creating a connection between a Java program and a MySQL database. The only thing not included in the code is the ConnectionValue
class which pulls all the relevant connection data needed for each specific connection/query. This class does work. When I run the code, it creates a NullPointerException
.
import javax.sql.rowset.CachedRowSet;
import java.sql.*;
public class SQLCommands {
private Connection connection;
private PreparedStatement preparedStatement;
private CachedRowSet cachedRowSet;
public void createConnection(ConnectionValues connectionValues) throws SQLException {
connection=DriverManager.getConnection(connectionValues.urlString,connectionValues.userName,connectionValues.password);
}
public void createCachedRowSet(ConnectionValues connectionValues, String query) throws SQLException {
cachedRowSet.setUsername(connectionValues.userName);
cachedRowSet.setPassword(connectionValues.password);
cachedRowSet.setUrl(connectionValues.urlString);
cachedRowSet.setCommand(query);
}
public void createPreparedStatement(CachedRowSet cachedRowSet) throws SQLException {
preparedStatement=connection.prepareStatement(cachedRowSet.getCommand());
}
public CachedRowSet readDataBase(int dbID, String query) throws Exception {
ConnectionValues connectionValues=new ConnectionValues(dbID);
createConnection(connectionValues);
System.out.println(connectionValues.urlString+"\n"+connectionValues.password+"\n"+connectionValues.userName);
createCachedRowSet(connectionValues,query);
createPreparedStatement(cachedRowSet);
try {
preparedStatement.execute();
return cachedRowSet;
}catch (Exception e){
System.err.print("ERROR!\nFunction: readDataBase\nClass: SQLCommands\n");
System.err.print(e);
}finally {
connection.close();
}
return cachedRowSet;
}
}
The stack trace reports that the error is occurring at line 14. Which is the cachedRowSet.setUsername(connectionValues.userName);
in the function createCachedRowSet
. The data is correct, I have a test print method that prints the relevant information in the code and it not only pulls the same data without error but also prints the correct information. So I'm not sure what is wrong. Knowing me, it's probably obvious but I can't see it.
@TeaDrinker ... Kindly Initialize cachedRowSet object which you have defined in line 7 but not initialized so at line 14 when you are setting property of cachedRowSet its throwing NullPointerException.