Exception - java.sql.SQLException: Operation not allowed after ResultSet closed - java

I am getting an exception like as
java.sql.SQLException: Before start of result set when calling getInt() method
My code is as follows:::
public void setdateTOSource(){
try{
String q = "SELECT * FROM ipp.resource;";
ResultSet result = DB_Access.getData(q);
System.out.println("Size result set"+result.getFetchSize());
while(result.next()){
getIpSource().add(result.getString(1));
System.out.println(result.getString(1));
}
System.out.println("source size "+getIpSource().size());
}
catch(Exception e){
System.out.println(e);
}
}
public void insertTargetToDb(List<String> targetValue){
try{
Connection con = DB_Connect.getDataBaseConnection();
Statement statement1 = con.createStatement();
int val=0;
String q1 = "SELECT MAX(area_id) as aa FROM ipp.area;";
ResultSet resultset = statement1.executeQuery(q1);
if(resultset.next()){
val = resultset.getInt(1);
};
val++;
String q2 = "INSERT INTO ipp.area VALUES("+val+",'"+getAreaName()+"',1);";
Statement statement2 = con.createStatement();
statement1.executeUpdate(q2);
for( int y=0;y<targetValue.size();y++){
System.out.println("FS");
String ip=targetValue.get(y);
System.out.println("ip" +ip);
String q3 ="SELECT resource_id FROM ipp.resource r where ip_address like '"+ip+"%';";
Statement statement3 = con.createStatement();
ResultSet resultset3 =statement3.executeQuery(q3);
System.out.println("FS1");
// ResultSet result1 =DB_Access.getData(q3);
System.out.println("FS2");
System.out.println("result set"+resultset3.getFetchSize());
//====================================================================
while(resultset3.next()){
setId(resultset.getInt(1));
}
System.out.println("result :........."+resultset3.getInt("resource_id"));
System.out.println("FS3");
String q4 = "INSERT INTO ipp.used_resource VALUES("+val+","+getId()+");";
Statement statement4= con.createStatement();
statement4.executeUpdate(q4);
// DB_Access.setData(q3);
statement3.close();
statement4.close();
// resultset3.close();
}
resultset.close();
statement1.close();
statement2.close();
con.close();
addMessage("Area created Successfully");
}
catch(Exception e){
System.out.println(e);
}
}
Exception comes after line
//==========================
resource_id is an integer value

This line
while(resultset3.next()){
setId(resultset.getInt(1));
}
must be replaced with?
while(resultset3.next()){
setId(resultset3.getInt(1));
}

Related

SQLServerResultSet:1 output instead of the data

I want my function to return the result of the Select statement, but in instead it prints SQLServerResultSet:1. How do I do to print/return the data in my function?
My function should execute the SQL statement and store the result in a variable.
public ResultSet selectSubmissions(int department) {
Connection connection = Database.getConnection();
String sql = "SELECT * FROM [MyDB_Widget].[dbo].[surveys] INNER JOIN [MyDB_Widget].[dbo].[instructors] ON surveys.instructor_id = instructors.instructor_id Where instructors.department_id = 2;";
ResultSet rs = null;
try {
Statement statement = connection.createStatement();
rs = statement.executeQuery(sql);
while (rs.next()) {
rs.getString(1); //or rs.getString("column name");
}
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
return rs;
}

How to retrieve all the name from MySQL?

I want to retrieve all the name and the number of row from MySQL to java. So far I only able to retrieve the total row number but I only get the last name. What's wrong here ?
StaffManagement.java
adminAPI api= new adminAPI();
try {
int num= api.displayCheckBoxAndLabel();
String allName= api.displayName();
System.out.println(num+allName);
}
adminAPI
public int displayCheckBoxAndLabel() throws Exception // get the number of row
{
int count = 0;
String sql="Select count(*) AS adminID from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
count= rs.getInt("adminID");
}
ps.close();
rs.close();
conn.close();
return count ;
}
public String displayName() throws Exception // get all the name
{
String name = null;
String sql="Select name from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
name= rs.getString("name");
}
ps.close();
rs.close();
conn.close();
return name ;
}
You currently return a single String, and your method iterates all of the admin names (but terminates after the final row, so that's your result). Instead, build a List of names and return that. You could also use a try-with-resources close to close your Connection, Statement and ResultSet instances. Something like
public List<String> displayName() throws Exception // get all the name
{
String sql = "Select name from admin";
List<String> names = new ArrayList<>();
DatabaseConnection db = new DatabaseConnection();
try (Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString("name"));
}
}
return names;
}
This might be helpful
private String names[];
int i = 0;
while (rs.next()) {
names[i] = rs.getString("name");
i++;
}
Then you can use a for loop to return each name in StaffManagement.java

Exhausted ResultSet Issue with Servlet Oracle

Every time I run this code it gives me an exhauset resultset error. Im not sure what Im doing wrong but Ive tried removing the .next(); code for either one or all resultsets and then the error given is the ResultSet next wasnt called.
Im not sure what Im doing wrong. Just curious what people might think the issue could be? Ive done similar earlier in my servlet code but only used 1 statement and then 1 prepared statement. This time Im using 2 statements and 1 prepared statement.
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
rs11.next();
ResultSet rs12 = stmt.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
rs12.next();
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
int olo1 = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)");
pstmt1.clearParameters();
pstmt1.setInt(1,olo);
pstmt1.setInt(2,olo1);
ResultSet rs1 = pstmt1.executeQuery();
rs1.next();
Some ideas on your code (in comments)
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
//Check if you HAVE a line here!
if(!rs11.next()) {
System.out.println("No Recipe Found");
}
//Use stmt1 - that's why you created it?!
ResultSet rs12 = stmt1.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
if(!rs12.next()) {
System.out.println("No Ingredient Found");
}
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
//Read Ingredient from rs12 -> that's where you selected it into
int olo1 = ((Number) rs12.getObject(1).intValue(); //convert resultset value to int
While this might point you into the right direction for solving the current issue, you should consider learning about clean code.
Consider this code making use of try-with-resource, refactored out some methods, using prepared statements.
//Replace exiting code
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
int recipieId = getRecipeId(con, opt1);
int ingredientId = getIngredientId(con, ingr1);
if(recipeId > 0 && ingredientId > 0) {
//Process result
insertRecLnk(con, recipeId, ingredientId);
} else {
System.out.println("No INSERT");
}
//Helper functions
protected int getRecipeId(Connection con, String rec) {
try(PreparedStatement st = con.prepareStatement("SELECT recipe_ID FROM GM_Recipes WHERE rec_name=?")) {
st.setString(1, rec);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Recipe Found");
return -1;
}
protected int getIngredientId(Connection con, String ing) {
try(PreparedStatement st = con.prepareStatement("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name=?")) {
st.setString(1, ing);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Ingredient Found");
return -1;
}
protected void insertRecLnk(Connection con, int rId, int iId) {
try(PreparedStatement ps = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)")) {
ps.setInt(1, rId);
ps.setInt(2, iId);
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
}
}

How to write variables inside Query language?

Example:
String s1;
String q = "select * from EntryByTitle where booktitle='"+s1+"'";
here in query statement why +s1+ is used in the syntax. As s1 is string, so it should be '"s1"'. But why '"+s1+"' is written in project.
Use a PreparedStatement and a bind parameter. This usually takes the form
String q = "select * from EntryByTitle where booktitle=?";
String bookTitle = "";
Connection conn = null;
try {
try (PreparedStatement ps = conn.prepareStatement(q)) {
ps.setString(1, bookTitle);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("booktitle"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}

Cause of parameter index out of range for code sample

Why am I getting "parameter index out of range (1>no. of parameters,which is 0)" for the code below?
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
String tabId = lblTableId.getText().trim();
try {
DBConnection db = new DBConnection();
Connection con = db.getConnectionMyWareHouse(Main.dwh.lblSessionWarehouse.getText());
String query1 = "Select DWTableId,DWTableName from datawarehousetable where DWTableId=? and DWTableName=? ";
System.out.println("OG Query ---->"+query1);
PreparedStatement ps1 = con.prepareStatement(query1);
ps1.setString(1, tabId);
ResultSet rs1 = ps1.executeQuery();
String strTN = "";
if(rs1.next())
{
strTN = rs1.getString("DWTableName");
}
String query2 = "Delete from datawarehousetable where DWTableId= ?";
System.out.println("OG Query ---->"+query2);
PreparedStatement ps2 = con.prepareStatement(query2);
ps2.setString(1, tabId);
int rs2 = ps2.executeUpdate();
String query3 = "Drop table " + strTN;
System.out.println("OG Query ---->"+query3);
PreparedStatement ps3 = con.prepareStatement(query3);
ps3.setString(1, tabId);
int rs3 = ps3.executeUpdate();
JOptionPane.showMessageDialog(null, "Table deleted successfully.", "Successful", JOptionPane.INFORMATION_MESSAGE);
con.close();
}
catch(Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error : " + e.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
}
}

Categories