Error in ResultSet Object [duplicate] - java

This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 5 years ago.
I'm thinking about the MVC application and for that and in the loading method of the lists that can be deleted with elements that are going to be chosen to make the query.
The classes associated with this are:
package modelo;
import java.sql.*;
import controlador.*;
public class CargaMenus {
public CargaMenus() {
miconexion = new Conexion();
}
public String ejecutaConsultas() { //Va a devolver el nombre de las tareas en el conbobox
Tareas miTarea = null;
Connection accesoBBDD = miconexion.dameConexion();
try {
Statement secciones = accesoBBDD.createStatement();
Statement descripciones = accesoBBDD.createStatement();
rs = secciones.executeQuery("SELECT DISTINCTROW NOMTAREA FROM TAREAS");
rs2 = descripciones.executeQuery("SELECT DISTINCTROW DESCTAREA FROM TAREAS");
miTarea = new Tareas();
miTarea.setNomtarea(rs.getString(1));
miTarea.setDesctarea(rs2.getString(1));
rs.close();
rs2.close();
} catch (SQLException e) {
System.out.println("Error en la conexión CARGAMENUS");
e.printStackTrace();
}
return miTarea.getNomtarea();
}
public Conexion miconexion;
public ResultSet rs;
public ResultSet rs2;
private String consulta = "SELECT DISTINCTROW NOMTAREA FROM TAREAS";
private String consulta2 = "SELECT DISTINCTROW DESCTAREA FROM TAREAS";
}
and the class that executes the method and travel what is returned by the database is:
package controlador;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.ResultSet;
import modelo.CargaMenus;
import vista.Marco_Aplicacion2;
public class ControladorCargaMenus extends WindowAdapter {
public ControladorCargaMenus(Marco_Aplicacion2 elmarco) {
this.elmarco = elmarco;
}
public void windowOpened(WindowEvent e) {
obj.ejecutaConsultas();
try {
while(obj.rs.next()) {
elmarco.secciones.addItem(obj.rs.getString(1));
}
while(obj.rs2.next()) {
elmarco.paises.addItem(obj.rs2.getString(1));
}
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
CargaMenus obj = new CargaMenus();
private Marco_Aplicacion2 elmarco;
}
When I run the program, I only see a combobox of the 2 that I designed.
and the following error
I thought the problem would be my sql queries but I validated them and there is no problem when I run them in my mysql.
and when I only load one of the lists (the first one) commenting the lines associated with the second list, the application loads me even if it throws errors in the console
The link I'm learning about is link of tutorial
How could I do to load the lists?

You should call rs.next before getting result.
if (rs.next()) {
miTarea.setNomtarea(rs.getString(1));
miTarea.setDesctarea(rs2.getString(1));
}

The root cause is that you are not calling rs.next() before rs.getString, it is only called after the ejecutaConsultas method is run. Same applies to rs2 usage.
Also you need to follow some best practices in your code such not exposing ResultSet to outside of your class and doing proper JDBC exception handling and closing of ResultSets andConnections.

Related

Got a NullPointerException in Servlet [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
*Well I have created a basic servlet program Where if user give their USN number correct it will fetch data from database else it will redirect to error.html
Whenever I Enter USN number it shows NullPointerException .Since I am using Eclipse There was No sign of error.
Note:I have Also Created a html file to enter the USN Number.
Code:
package com.abc.error;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetResult extends HttpServlet {
/**
*
*/
static final long serialVersionUID = 1L;
Connection con= null;
PreparedStatement pstmt=null;
ResultSet res=null;
public void init(){
try {
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#//localhost:1521/XE","system","system");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
#Override
public void service(HttpServletRequest request, HttpServletResponse response) {
try
{
pstmt = con.prepareStatement("SELECT * FROM VTURESULT_AUG WHERE USN =?");
String key = request.getParameter("USN");
if(key.length()!=12){
response.sendRedirect("/ServletWithError/error.html");
}
else
{
pstmt.setString(1,key);
res =pstmt.executeQuery();
if(res.next())
{
String usn = res.getString(1);
String name = res.getString(2);
int m1 = res.getInt(3);
int m2 = res.getInt(4);
int m3 = res.getInt(5);
PrintWriter pw =response.getWriter();
pw.println(usn+" "+name+" "+m1+" "+m2+" "+m3);
}
}
}
catch(SQLException | IOException e)
{
e.printStackTrace();
}
}
}
Output:
java.lang.NullPointerException
com.abc.error.GetResult.service(GetResult.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
The stacktrace says the NPE is at this line if the posted code's line numbers match your actual code:
pstmt.setString(1,key);
You can verify this by setting a breakpoint on that line.
I can't see your actual code, so there are a couple of things you should check using more breakpoints:
Is con null? If so, your init() method may not be getting called, or it's throwing an exception higher up in your log that you're not seeing.
Move your PreparedStatement declaration down to where it's being used - declaring it outside the function isn't helping you at all in this case:
PreparedStatement stmt = con.prepare(...);
And of course, verify that key is non-null.

Exhausted resultset java sqlexception

i've been getting the error exhausted resultset without really knowing what's wrong with what i'm doing, i'm basically trying to stock 3 rows from a database to an array of 3 elements of a class called "Logement" in my uni project which will be later used to fill a number of checkboxes in a javafx ui
package accesBD;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import metier.ConvIntToBool;
import metier.Logement;
public class LogementDAO {
TypeLogementDAO bd = new TypeLogementDAO();
public Logement[] findAll() throws SQLException {
Logement logements[] = null;
Connection cnx= SConnection.getInstance();
Logement logement = null;
try {
PreparedStatement st= cnx.prepareStatement("select* from logement");
ResultSet res= st.executeQuery();
int i =0;
while (res.next()) {
logement= new Logement(bd.find(res.getInt(1)), ConvIntToBool.boolToInt(res.getInt(2)) ,ConvIntToBool.boolToInt(res.getInt(3)),ConvIntToBool.boolToInt(res.getInt(4)),ConvIntToBool.boolToInt(res.getInt(5)),ConvIntToBool.boolToInt(res.getInt(6)));
//System.out.println(res.getRow());
logements[i]=logement;
i++;
}
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
return logements;//la collection retournée peut être vide
}
}
These are the 3 rows that i'm trying to receive from the database
and this is the code for the method find
public TypeLogement find(int id){
Connection cnx =SConnection.getInstance();
TypeLogement c=null;
try {PreparedStatement stp1=cnx.prepareStatement("select * from typelogement where id=?");
stp1.setInt(1, id);
ResultSet n= stp1.executeQuery();
while(n.next()){
c= new TypeLogement(n.getInt(1),n.getString(2),n.getDouble(3));
}
cnx.close();
} catch (SQLException e) {
e.printStackTrace();
}
return c;
}
Looks like the issue is because you close database connection:
You use Connection cnx= SConnection.getInstance(); to get connection in both findAll() and find(). And in find() you close connection. So the following happens:
You open connection in findAll()
You get outer ResultSet and iterate over it
In the loop you call find()
You call Connection cnx= SConnection.getInstance(); and get inner ResultSet
You close connection in find(). When you close connection it closes all result sets opened in that connection
Loop for outer ResultSet fails since result set was closed due to closed connection in find() method
Instead of closing connection you need to close ResultSet in find() method.

com.mysql.jdbc.exception.jdbc4.MySQLNonTransientConnectionException: No operation allowed after connection closed

how to solve this problem and what is wrong in this code?
i know that the question has been asked before but i cant solve the problem
private void cb_categoriesPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
cb_categories.removeAllItems();
try {
String sql_c = "SELECT * FROM inventory.categories";
cc.pst = cc.c.prepareStatement(sql_c);
cc.rs = cc.pst.executeQuery();
while (cc.rs.next()) {
String c_name = cc.rs.getString("CategoryName");
cb_categories.addItem(c_name);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
} finally {
try {
cc.rs.close();
cc.pst.close();
} catch (Exception e) {
}
}
}
Your ResultSet and PreparedStatement are not declared in method scope, so I have to assume that you've declared them elsewhere.
That's a big mistake.
You should declare the Statement and ResultSet in method scope.
You make an attempt to close your resources, but you should wrap them in individual try/catch blocks. You cannot risk one being closed and not the other.
There are other things I'd criticize about your code (e.g. SELECT *, mingling UI and database code together in a single class), but that's enough to start.
Start with an interface:
package persistence;
import java.util.List;
/**
* Created by Michael
* Creation date 8/20/2017.
* #link https://stackoverflow.com/questions/45787151/com-mysql-jdbc-exception-jdbc4-mysqlnontransientconnectionexception-no-operatio/45787321?noredirect=1#comment78532554_45787321
*/
public interface CategoryDao {
List<String> findAllCategories();
}
Then write a concrete implementation:
package database;
import database.util.DatabaseUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Michael
* Creation date 8/20/2017.
* #link https://stackoverflow.com/questions/45787151/com-mysql-jdbc-exception-jdbc4-mysqlnontransientconnectionexception-no-operatio/45787321?noredirect=1#comment78532554_45787321
*/
public class CategoryDaoImpl implements CategoryDao {
private static final Log LOGGER = LogFactory.getLog(CategoryDaoImpl.class);
private static String SELECT_CATEGORIES = "SELECT CategoryName from inventory.Categories ";
private DataSource dataSource;
public CategoryDaoImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<String> findAllCategories() {
List<String> categories = new ArrayList<>();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = this.dataSource.getConnection().prepareStatement(SELECT_CATEGORIES);
rs = ps.executeQuery();
while (rs.next()) {
categories.add(rs.getString("CategoryName"));
}
} catch (SQLException e) {
LOGGER.error(String.format("Exception caught while selecting all category names"), e);
} finally {
DatabaseUtils.close(rs);
DatabaseUtils.close(ps);
}
return categories;
}
}
This is something that you can test with JUnit off to the side. Get it running perfectly, then give a reference to your UI code. It'll keep the UI and database code separate. You can use this DAO in any application without worrying about Swing or web UI.

Having trouble returning an array list [duplicate]

This question already has answers here:
Problem with "scopes" of variables in try catch blocks in Java
(3 answers)
Closed 6 years ago.
I'm working on a personal project and I'm fairly new at java (trying to create a web application). I'm having some issues returning an arraylist that I've defined earlier in the method. The arraylist prints normally but for some reason my IDE is saying it's not defined when I try to return it. Here's my code, and thanks for any help:
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.mysql.jdbc.Statement;
public class Fire_Emblem {
public static ArrayList<String> GetCharacters() {
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/fire_emblem","root","[redacted]");
java.sql.Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select name from characters");
System.out.println ("Connection successful");
ArrayList<String> list = new ArrayList<String>();
while (rs.next()) {
list.add(rs.getString("name"));
}
System.out.println(list);
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.out.println("Connection failed");
}
return list;
}
}
You created the list within the scope of the try block. Define it before try.
If nothing is referencing list after the program leaves the scope where it was created, then the object will be destroyed. For more on this topic look here
ArrayList<String> list = new ArrayList<String>();
try {
...
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.out.println("Connection failed");
}
return list;
The list variable is inside the try {} scope. You are referencing the list variable outside its scope.
The IDE tells you Cannot resolve symbol 'list' which means the variable is not defined in this scope.

How do I call variables from a Java class into another Class?

I've read about inheritance or using the import. I just simply am unable to get the right answer. Firstly my code is of the following form:
class queries{
String query1="Select * from "+tableName+";
String query2="Select "+columnName+" from "+tableName+";
}
Now, I have another class where I wish to make make SQL queries using the queries mentioned in the queries class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
class test{
public static void main(String args[])throws SQLException
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("This is Wrong");
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection connect = DriverManager
.getConnection("SQLCONNECTION");
PreparedStatement preparedStatement = connect
.prepareStatement(THIS SHOULD CALL query1 or query2);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("THIS RUNS");
//display text
}
preparedStatement.close();
connect.close();
}
}
So well, I need to figure out how to call query1 or query2 from the queries class in test. Sorry, but I hope someone can help me how to do this in a clean way. I can also create a Hashtable in queries where I call the respective query based on its name.
Thanks a lot.
class queries
{
public static String getQuery1(String tableName)
{
return "Select * from "+tableName;
}
public static String getQuery2(String tableName, String columnName)
{
return "Select "+columnName+" from "+tableName;
}
}
Then do this:
PreparedStatement preparedStatement =
connect.prepareStatement(queries.getQuery1("INSERT TABLE NAME HERE"));

Categories