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.
Related
I am very new to Java and am simply trying to connect to my MSSQL database and return a list of customers. When I try the JDBC connection, I get a "no suitable driver found" error. When I add a Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") statement, I get a ClassNotFound error. This seems like it should be a lot easier than it's turning out to be. Please help me either find a suitable driver or how to get access through the Class.forName usage.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbConn {
public static String getConnString(){
return "jdbc:sqlserver://localhost\\SQLEXPRESS:1433;database=OhHold;";
}
public static void getConnection() {
try
{
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String user = "<USER>";
String pw = "****************";
Connection connection = DriverManager.getConnection(getConnString(), user, pw);
Statement statement = connection.createStatement();
String sql = "select txtCompanyName as company from tblCustomers where intNotActive <> 1";
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
System.out.println(result.getString(1));
}
}
/*
// Handle any errors that may have occurred.
catch (ClassNotFoundException e) {
e.printStackTrace();
}
*/
catch (SQLException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
getConnection();
}
}
My SQL connection keeps saying it's busy even though all previous connections are closed.
The error below results. All others are either closed by the exiting of the JFrame or the .close() method. Does anyone see anything wrong with the class? (All other classes work as intended.)
SEVERE: null
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.execute(DB.java:854)
at org.sqlite.core.DB.executeUpdate(DB.java:895)
package teacherreviewproject;
//initialise imports
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class FeedbackForm extends javax.swing.JFrame {
//init. variables
String WWW;
String EBI;
int rating;
String teacher;
String studentUser;
String ratingraw;
String teacherQuery;
public FeedbackForm(String s) {
initComponents();
getTeachersNames();
this.studentUser = s;
}
private void getTeachersNames(){
//get the connection
Connection con = DBConnection.getConnection();
//set up query string
this.teacherQuery = "SELECT * FROM users WHERE type=2";
try {
//prepare statement
PreparedStatement teacherState = con.prepareStatement(teacherQuery);
//execute query
ResultSet teachResult = teacherState.executeQuery();
//clear previous items to avoid duplicates.
jComboBox_teachers.removeAllItems();
//create counter variable to get different teachers in RS
int i = 0;
//while loop
while(teachResult.next()){
//get username then add it to position i at combobox
String tempOption = teachResult.getString("username");
System.out.println(tempOption);
jComboBox_teachers.addItem(tempOption); //thanks mcalpine
//increment i
i++;
}
} catch (SQLException ex) {
Logger.getLogger(FeedbackForm.class.getName()).log(Level.SEVERE, null, ex);
}
Found the bug! I needed to make a close-if feature on my Connection class.
Here's the code, should anyone want it:
public class DBConnection{
public static Connection con = null;
public static Connection getConnection(){
//initialise connection
try{
//creates valid url to access DB with
String url = "jdbc:sqlite:" + System.getProperty("user.dir") + "/TeacherReviewIA.DB";
if(con == null){
con = (Connection) DriverManager.getConnection(url);
}else{
con.close();
con = (Connection) DriverManager.getConnection(url);
}
//as a debug measure and to show connection given
System.out.println(con);
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex,"WARNING",JOptionPane.WARNING_MESSAGE);
}
//allows code that called method to use connection given
return con;
}
}
I would like to make a mysql database query in a Java code and if the value from the database is true for example then a certain code should be executed and if the value is false the program should close but I have the problem that I get the value from the database is not formatted so that I can make an IF query. if I could not explain this in a very understandable way, I hope that you can find out from the code in the appendix
//imports
package de.alphaalmann.troll;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.sql.*;
public class Main extends JavaPlugin {
public static void main(String[] args) {
//databaseconnetion
String url = "jdbc:mysql://localhost/plugin?useJDBC";
String user = "plugin";
String password = "uwu3000";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("sucsesful");
PreparedStatement stmt = conn.prepareStatement("SELECT STATUS FROM plugin WHERE NAME="trollpl"");
stmt.execute();
System.out.println(stmt);
stmt.close();
//if-query if it true,
if(stmt==true) {
//if it true execute this
//else this part
}else {
System.out.println("error");
}
}catch(SQLException ex) {
System.err.println(ex.getMessage());
}
}
}
highling.
You'll need a ResultSet object in order to receive the query results, get the results and then close the PreparedStatement.
Something like this:
int result;
ResultSet rs = stmt.execute();
if(rs.next()){
// I don't know what your query returns
//I'll assume you use only the first result , it'll be an int
result = rs.getInt(1);
}
stmt.close();
// Now you decide what to do with result.
HTH,
WB::
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.
I am using a restful web service and I was able to display database records using an array. But I am confused on how will I be able to display my desired record. I have here the class where the SQL query is being executed. I am using Advanced Rest Client google chrome application in testing the response and the output. How will I be able to query 'select * from taxi where taxi_plate_no='inputted data''? I am really confused on how will I be able to do it in an array. Please help me. Thank you! :(
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.ws.rs.QueryParam;
import com.taxisafe.objects.Objects;
public class DisplayArrayConnection
{
public ArrayList<Objects> getDetails(Connection con) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM taxi");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Objects detailsObject = new Objects();
detailsObject.setTaxi_name(rs.getString("taxi_name"));
detailsObject.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiDetailsList.add(detailsObject);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return taxiDetailsList;
}
}
#QueryParam is annotation used in rest webservices .
And i think here you want to use parameter with your SQL query.
So using parameter in PreparedStatement use following code
public class DisplayArrayConnection
{
public ArrayList<Objects> getDetails(Connection con,String taxiNumber) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM taxi WHERE taxi_plate_no= ?");
stmt.addString(1,taxiNumber);
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Objects detailsObject = new Objects();
detailsObject.setTaxi_name(rs.getString("taxi_name"));
detailsObject.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiDetailsList.add(detailsObject);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return taxiDetailsList;
}
}
Note: Use parameter taxiNumber or any other parameter you want to
retrive data on that parameter
and use setString(position,value); to replace ? with that parameter