Resultset To List null [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 10 months ago.
public List<Order> getAllOrdersByCustomerId(int customerId) throws SQLException {
List<Order> AllOrdersByCustomerId = new ArrayList<>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sqlQuery = "SELECT * FROM dbo.Orders WHERE customer_id = ?";
con = JDBCConnection.getConnection();
pstmt = con.prepareStatement(sqlQuery);
pstmt.setInt(1, customerId);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
JDBCConnection.closeConnection(con);
}
if (rs != null) {
JDBCConnection.closeResultSet(rs);
}
}
return AllOrdersByCustomerId;
}
//Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.iterator()" because "lo" is null

You should use ResultSet to read your Order of SQL query, and add the Order into your List, like below:
public List<Order> getAllOrdersByCustomerId(int customerId) throws SQLException {
List<Order> allOrdersByCustomerId = new ArrayList<>();
String sqlQuery = "SELECT * FROM dbo.Orders WHERE customer_id = ?";
try (Connection con = JDBCConnection.getConnection();
PreparedStatement pstmt = con.prepareStatement(sqlQuery)) {
pstmt.setInt(1, customerId);
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
Order order = new Order();
String id = rs.getString("ORDER_ID");
order.setId(id);
// get and set your values ...
allOrdersByCustomerId.add(order);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return allOrdersByCustomerId;
}

Related

What is the right way to deal with the PreparedStatement in the Java program flow?

There are two methods in which the PreparedStatement is used.
The first method is called in the second method.
First method:
protected List<String> findResultsByMandantId(Long mandantId) {
List<String> resultIds = new ArrayList<>();
ResultSet rs;
String sql = "SELECT result_id FROM results WHERE mandant_id = ?";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.setLong(1, mandantId);
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
resultIds.add(rs.getString(1));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return resultIds;
}
Second method:
protected void findResultLineEntityToDelete(Long mandantId, String title, String context) {
List<String> resultIds = findResultsByMandantId(mandantId);
String [] resultIdsArr = resultIds.toArray(String[]::new);
ResultSet rs;
//String sql = "SELECT * FROM resultline WHERE result_id in (SELECT result_id FROM results WHERE mandant_id =" + mandantId + ")";
String sql = "SELECT * FROM resultline WHERE result_id in (" + String.join(", ", resultIdsArr)+ ")";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
if (rs.getString(3).equals(title) && rs.getString(4).equals(context)) {
System.out.println("Titel: " + rs.getString(3) + " " + "Context: " + rs.getString(4));
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
The class in which both methods are located extends the JDBCBaseManager.
JDBCBaseManager:
private final String url = "jdbc:mysql://localhost:3306/database";
private final String userName = "root";
private final String password = "";
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private int batchSize = 0;
public JDBCBaseManager() {
// Dotenv env = Dotenv.configure().directory("./serverless").load();
// url = env.get("DB_PROD_URL");
// userName = env.get("DB_USER");
// password = env.get("DB_PW");
}
public void getConnection() {
try {
if (connection == null) {
connection = DriverManager.getConnection(url, userName, password);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
if (connection == null) {
getConnection();
}
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void closeConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void startBatch(int batchSize) throws SQLException {
connection.setAutoCommit(false);
setBatchSize(batchSize);
}
public void commit() {
try {
if (connection != null && !connection.isClosed()) {
connection.commit();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
The ResultSet in the second method still contains the results from the first method.
I already tried to close the connection and open it again before the second method is executed, but then I get the errors:
java.sql.SQLException: No operations allowed after statement closed.
java.sql.SQLNonTransientConnectionException: No operations allowed
after connection closed.
Can you tell me how to deal with the statement correctly in this case? Is my BaseManager incorrectly structured?
Here lies the error
public JDBCBaseManager() {
private PreparedStatement preparedStatement = null;
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
......
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
You build the prepare statement only the first time the method getPreparedStatement is called because only the first time the field preparedStatement is null. Every next time you call the method getPreparedStatement you receive the previous preparedStatement from the previous SQL and not the new one.
Remove the check for if (preparedStatement == null) {
You need to build a new preparedStatement every time you want to execute a new SQL.

try-with-resources JDBC with multiple resources and an else statement

This is a method to add a new planet to an observablelist of customers.
I am wondering if I am using the try with resources correctly and if the auto-close is working.
public static Customer addPlanet(Customer customer) {
String query1 = "Select * from planet where planet=? AND universeID=?";
String query2 = "INSERT INTO planet (planet,universeID) VALUES(?,?)";
try (PreparedStatement statement = (PreparedStatement) Database.connection.prepareStatement(query1);
PreparedStatement statement2 = (PreparedStatement) Database.connection.prepareStatement(query2)) {
statement.setString(1, customer.getPlanet());
statement.setString(2, Integer.toString(customer.getUniverseID()));
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
int planetId = rs.getInt(1);
customer.setPlanetID(planetId);
return customer;
} else {
statement2.setString(1, customer.getPlanet());
statement2.setInt(2, customer.getUniverseID());
statement2.executeUpdate();
return addPlanet(customer);
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
} catch (SQLException e) {
e.printStackTrace();
}
return customer;
}
My question is, does this part need to be enclosed in a try-catch block or does it get closed automatically.
statement2.executeUpdate();
It gets closed. Anything in the try gets closed at the end if they are AutoCloseable.

How to use a variable value declared in servlet into a new Java class?

I have a login servlet where I have a login query in my post method from the query I am getting username, password, company name and ID
I am storing all this values in a variable like
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String companyDB,nameDB,idDB;
try {
con = DBConnection.createConnection();
statement = con.createStatement();
String sql = " SELECT MT_USERS.MT_USERS_VCLOGINCODE AS USERID, MT_USERS.MT_USERS_VCUSERPASSWORD AS PASSWORDID, MT_USERS.MT_USERS_VCUSERNAME AS NAME, (SELECT MT_DISTRIBUTR_VCDISTRIBUTRNAME FROM MT_DISTRIBUTR WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS COMPANYNAME ,(SELECT mt_distributr_vcdistributrcode FROM mt_distributr WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS ID FROM MT_USERS WHERE MT_USERS_VCLOGINCODE='admin' AND MT_USERS_VCUSERPASSWORD ='admin'";
resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
companyDB = resultSet.getString("COMPANYNAME");
nameDB = resultSet.getString("name");
idDB = resultset.getString("ID");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Now I have an another class where I am writing a query and in that query I want to use idDB like
My new class is
public class Outlet {
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
public List<String> getoutlet() throws ClassNotFoundException, SQLException {
List<String> list = new ArrayList<String>();
con = DBConnection.createConnection();
statement = con.createStatement();
try {
ResultSet resultSet = statement.executeQuery("select * from ecustomer where CUSTOMERIDENTIFIER in(select CUSTOMERIDENTIFIER from mt_distributrol where mt_distributr_vcdistributrcode = 'AAAA'");
while (resultSet.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
Where mt_distributr_vcdistributrcode = 'AAAA'" at the place of 'AAAA' I have to pass a variable which has the value of idDB
You may use a prepared statement here:
String sql = "SELECT CUSTOMERDESCRIPTOR FROM ecustomer WHERE CUSTOMERIDENTIFIER IN (";
sql += "SELECT CUSTOMERIDENTIFIER FROM mt_distributrol ";
sql += "WHERE mt_distributr_vcdistributrcode = ?)");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "AAAA");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
I actually find that MkYong does a good job of explaining prepared statements in Java, see here, but any good documentation is a good place to start looking. And see Oracle Tutorial.

Findbugs error "Load of known null value" SQL connection

I have DAO class with methods getting and sending data.
I'm catching Exceptions inside SQL requests, so I need to declare connection variables outside of try parenthesis.
every method looks lookes like this:
public Role getRole(int roleId) {
Connection connection = null;
ResultSet rs = null;
PreparedStatement statement = null;
Role role = null;
try {
connection = dataSource.getConnection();
statement = connection.prepareStatement("select ROLE_ID, ROLE_TEXT from ROLES WHERE ROLE_ID = :1");
statement.setInt(1, roleId);
rs = statement.executeQuery();
rs.next();
role = roleMapper.mapRow(rs, 1);
} catch (SQLException e) {
} finally {
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeStatement(statement);
JdbcUtils.closeConnection(connection);
return role;
}
}
But there's problem. Finbugs giving me an error, saying:
Load of known null value in DAO.getRole
and
may fail to clean up java.sql.Statement
So what should I do to avoid that?
The getRole can return null.
Furthermore:
if (rs.next()) {
role = roleMapper.mapRow(rs, 1);
}
I prefer another notation. And the error solution unfortunately consists of either letting getRole throw an exception (best) or letting return an Optional<Role>
//public Role getRole(int roleId) throws SQLException {
public Optional<Role> getRole(int roleId) {
try (Connection connection = dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement(
"select ROLE_ID, ROLE_TEXT from ROLES WHERE ROLE_ID = :1")) {
statement.setInt(1, roleId);
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
return roleMapper.mapRow(rs, 1);
}
}
} catch (SQLException e) { //
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ID: " + roleId, e); //
}
return Optional.empty(); //
}

Preparedstatement java

I want to look for something that matches a enum: Divisions:U6,U7,U8...
It works when i do this.
public ArrayList<Training> zoekTrainingen(Ploegen p) throws
ApplicationException {
ArrayList<Training> tr = new ArrayList<>();
Connection conn = ConnectionManager.getConnection(driver,
dburl, login, paswoord);
try (PreparedStatement stmt = conn.prepareStatement(
"select * from trainingen");) {
stmt.execute();
ResultSet r = stmt.getResultSet();
while (r.next()) {
---
}
} catch (SQLException sqlEx) {
throw new ApplicationException("");
}
finally {
return tr;
}
}
}
but when I do this:
try (PreparedStatement stmt = conn.prepareStatement(
"select * from trainingen where Divsion = ?");) {
stmt.setString(1, p.getDivision());
I get nothing
The code is attempting to set a String parameter using an Enum. It should get the String value of the Enum and pass to the setString method.
try (PreparedStatement stmt = conn.prepareStatement(
"select * from trainingen where Divsion = ?");) {
stmt.setString(1, p.getDivision().toString());

Categories