ResultSet is getting closed on executing statement.execute(sql) - resultset

On executing the follwing code i am getting error java.sql.SQLException: ResultSet is closed
public class SavePoints {
public void extract(ResultSet rs)
{
int c;
try {
while(rs.next())
{
c = rs.getInt("id");
String d=rs.getString("name");
String e=rs.getString("city");
String f=rs.getString("state");
String g=rs.getString("country");
//Displaying values
System.out.println("ID is:"+c+"\tName is:"+d+"\tCity is:"+e+"\tState is:"+f+"\tCountry is:"+g);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
SavePoints spobj=new SavePoints();
try {
Connection con=DriverManager.getConnection("jdbc:odbc:Divya", "SYSTEM", "tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from publishers");
spobj.extract(rs);
//DatabaseMetaData databaseMetaData = con.getMetaData();
//System.out.println(databaseMetaData.getDriverMajorVersion());
//Savepoint sp=con.setSavepoint("Deleting Rows");
st.execute("delete from publishers where id=104");
//con.rollback(sp);
spobj.extract(rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What is the error? I cannot find it. Please let me know. I am a newbie.. so please explain in simple terms. I am grateful for your help. Thanks :)

you have called spobj.extract(rs); twice ,
first time when this function executes resultset moves to last because you are using rs.next()..
to achieve this you have use scrollable resultset
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
and for next call of spobj.extract(rs); reverse the call of resultset by rs.previous()

Related

data provider mismatch error

I am using below code for data provider but it's not working. Please help to me how to resolve data provider mismatch issue. here mentioned complete details about all the methods reading xls , test , data provider .
#DataProvider
public Object[][] getgbTestData(){
Object data[][] = testutil.getTestData(sheetName);
return data;
}
#Test(dataProvider="getgbTestData")
public void addnewuser(String fname,String lname,String email,String pass,String conpass) throws IOException{
newuser.newregistration1(fname, lname, email, pass, conpass);
}
**method:**
public Personaldetails newregistration1(String fsname,String lsname,String email1,String pass1,String conpass1) throws IOException {
Account.click();
Registerlink.click();
Firstname.sendKeys(fsname);
Lastname.sendKeys(lsname);
useremail.sendKeys(email1);
password.sendKeys(pass1);
confirmpassword.sendKeys(conpass1);
submit.click();
//return person;
return new Personaldetails();
}
//using below method to read data from excel
public static Object[][] getTestData(String sheetName) {
FileInputStream file = null;
try {
file = new FileInputStream(TESTDATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetName);
Object[][] data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
// System.out.println(sheet.getLastRowNum() + "--------" +
// sheet.getRow(0).getLastCellNum());
for (int i = 0; i < sheet.getLastRowNum(); i++) {
for (int k = 0; k < sheet.getRow(0).getLastCellNum(); k++) {
data[i][k] = sheet.getRow(i + 1).getCell(k).toString();
// System.out.println(data[i][k]);
}
}
return data;
}
Looks like the test has required 5 arguments but your data provider method getTestData passing less/greater no of arguments.
You are passing the wrong number of arguments. The method addnewuser() expects 5 arguments, but receives only one. You can see it in the last line in the error message
Arguments: [(java.lang.String)fname]
If you want to pass different number of parameters you can use String[] instead of single arguments. And if you expect 5 arguments each time check what data holds in getTestData()

how am i supposed to pull a record from DAO vector?

I'm trying to implement the login page based on Oracle sql using JFrame(swing). I already have inserted IDs and PWs on database. Plus, I've also already defined appropriate -I think- LoginMember method in DAO. Below are the codes for Jframe page and DAO. Please let me know what is wrong with this. I've been struggling with this for the last 5 hours and still have no idea what to do.. HELP!! Sorry if you feel that I have not given enough info to solve this problem.
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strID=tfID.getText();
String strPW=String.valueOf(pwfPW.getPassword());
if(tfID.getText().equals("")) {
JOptionPane.showMessageDialog(Login.this, "Please type your ID");
} else {
dao=new M_DAO();
dao.loginMember(strID,strPW);
if(tfID.getText().equals(dao.loginMember(strID,strPW))) {
JOptionPane.showMessageDialog(Login.this, strID+" : successfully logged in");
}else if(strID ==null && strID.equals(strPW)){
JOptionPane.showMessageDialog(Login.this, "Incorrect ID or PW.");
}else{
System.out.println(10);
}
}
}
});
DAO:
public Vector loginMember(String strID,String strPW) {
Vector items=new Vector();
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
conn=DB.hrConn();
String sql="select * from member where strID=? and strPW=?";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, "strID");
pstmt.setString(2, "strPW");
rs=pstmt.executeQuery();
if(rs.next()){
Vector row=new Vector();
row.add("strID");
row.add("strPW");
items.add(row);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(pstmt!=null) pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return items;
}
I wish it would work so bad...
It only shows the correct answer when I type nothing on ID and PW textfields, saying "Please type your ID". It prints out 10 when I type something on those.(just to check which line has an error.) Oh, please let me know if I need to specify something else!

Reading a table from database

I having a problem to run below Java code. I couldn't find the DB.java class.
ResultSet rs = DB.getConnection().createStatement().executeQuery("select * from products");
while(rs.next()){
System.out.print(rs.getString("pid"));
System.out.print(rs.getString("name"));
System.out.print(rs.getString("price"));
System.out.print(rs.getString("ava_qty"));
}
I'm using Glassfish server. Can someone help me to write the DB.java class?
The getConnection() method is part of the DriverManager class. Initialize your drivermanager properly, as described in this post:
https://www.tutorialspoint.com/javaexamples/jdbc_dbconnection.htm
Example code for future reference:
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
System.out.println("JDBC Class found");
int no_of_rows = 0;
try {
Connection con = DriverManager.getConnection (
"jdbc:derby://localhost:1527/testDb","username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");
while (rs.next()) {
no_of_rows++;
}
System.out.println("There are "+ no_of_rows + " record in the table");
} catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}

Inserting Error

I'm trying to insert in postgresql db date, but when I'm inserting it, I'm getting this error:
Error occurred while INSERTING operation: org.postgresql.util.PSQLException: ERROR: column "text that i wrote" does not exist"
I don't understand what did I code wrong that, program tries to find column in values?
But when I try to output this table, it outputs without errors
WORKERDAO class
public static void insertWrk(String name, String post) throws SQLException, ClassNotFoundException {
//Declare a INSTERT statement
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"("+name+","+post+");";
//Execute INSTERT operation
try {
DBUtil.dbExecuteUpdate(updateStmt);
} catch (SQLException e) {
System.out.print("Error occurred while INSTERING Operation: " + e);
throw e;
}
}
DBUTIL class
public static void dbExecuteUpdate(String sqlStmt) throws SQLException, ClassNotFoundException {
//Declare statement as null
Statement stmt = null;
try {
//Connect to DB
dbConnect();
//Create Statement
stmt = conn.createStatement();
//Run executeUpdate operation with given sql statement
stmt.executeUpdate(sqlStmt);
} catch (SQLException e) {
System.out.println("Проблема в выполнение executeUpdate операции : " + e);
throw e;
} finally {
if (stmt != null) {
//Close statement
stmt.close();
}
//Close connection
dbDisconnect();
}
}
WorkerController Class
#FXML
private void insertWorker (ActionEvent actionEvent) throws SQLException, ClassNotFoundException {
try {
WorkerDAO.insertWrk(nameText.getText(),postCombo.getSelectionModel().getSelectedItem());
} catch (SQLException e) {
System.out.println("Problem occurred while inserting worker " + e);
throw e;
}
}
You need to put quotes around the data you're inserting:
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"("+name+","+post+");";
Should be:
String updateStmt ="INSERT INTO worker(full_name,post)" +
"VALUES" +
"('"+name+"',"'+post+'");";
Be aware that you're risking SQL Injection attacks using this method, see about using a parameterised insert. This site lists a bit more detail.

SQL Server, JTDS causes java.sql.SQLException: Invalid state, the ResultSet object is closed

I am using Tomcat 7, Microsoft SQL Server 2008 RC2 and JTDS driver
I am actually using C3P0 as well to try and solve this problem, but it makes no difference at all. I was using Microsoft's driver but it caused me other problems (the requested operation is not supported on forward only result sets)
I get the following error, always at the same point. I have successfully run other queries before getting to this point:
java.sql.SQLException: Invalid state, the ResultSet object is closed.
at
net.sourceforge.jtds.jdbc.JtdsResultSet.checkOpen(JtdsResultSet.java:287)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.findColumn(JtdsResultSet.java:943)
at
net.sourceforge.jtds.jdbc.JtdsResultSet.getInt(JtdsResultSet.java:968)
at
com.mchange.v2.c3p0.impl.NewProxyResultSet.getInt(NewProxyResultSet.java:2573)
at com.tt.web.WebPosition.createPosition(WebPosition.java:863)
The code is as follows:
public static List getListPositions(String query) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
List list = null;
try { //execute the sql query and create the resultSet
con = DBConnection.getInstance().getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()) {
if(rs.isFirst()) {
list = new ArrayList();
}
WebPosition webPos = null;
webPos = new WebPosition(rs);
list.add(webPos);
}
} catch (java.sql.SQLException e) {
System.out.println("SQLException in getListPositions");
System.out.print(query);
Log.getInstance().write(query);
Log.getInstance().write(e.toString());
} catch (Exception ex) {
System.out.print(ex);
ex.printStackTrace();
Log.getInstance().write(ex.toString());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
Log.getInstance().write(e.toString());
}
}
DBConnection.getInstance().returnConnection(con);
}
return list;
}
public WebPosition(ResultSet rs) {
createPosition( rs);
}
public void createPosition(ResultSet rs) {
try {
this.setCurrentDate4Excel(rs.getString("SYSDATE_4_EXCEL"));
this.setExerciseType(rs.getInt("EXERCISE_STYLE_CD"));
...
The code fails in between the above two lines.
I am at a loss to explain why the Result set would be closed in the middle of a function (i.e. it would retrieve rs.getString("SYSDATE_4_EXCEL") but then fail with the error posted at the line rs.getInt("EXERCISE_STYLE_CD"))
Does anyone have any ideas? I imagine that it is some kind of memory issue, and that the connection is automatically closed after a certain amount of data, but I am not sure how to fix this. I tried increasing the heapsize for the JVM.