Maverick
Maverick

Reputation: 292

executeUpdate() returns zero despite correct execution

create_PaperBean.java

package Beans;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class create_paperBean extends org.apache.struts.action.ActionForm {

    private String table_name;

    public String getTable_name() {
        return table_name;
    }

    public void setTable_name(String table_name) {
        this.table_name = table_name;
    }
    public String createDB(){
        String str = "creation_failed";
        try{   
            Statement st = DBConnection.DBConnection.DBConnect();
            int insert = st.executeUpdate("CREATE TABLE "+table_name+"(ques_no int(11) NOT NULL PRIMARy KEY,"
                    + "ques_name varchar(45),ans1 varchar(45),ans2 varchar(45),ans3 varchar(45),"
                    + "ans4 varchar(45),correct_ans varchar(45))");            
            System.out.println(insert);
            if(insert > 0)
                str = "created";            
        } catch (SQLException ex) {
            Logger.getLogger(create_paperBean.class.getName()).log(Level.SEVERE, null, ex);
        }  
        return str;
    }
}

I'm using struts and when this bean is executed a table is created in the database, but the value of insert is still zero! Therefore I can't proceed to the correct page for further functioning of the web app. What am I doing wrong?

Upvotes: 1

Views: 21339

Answers (3)

Azad
Azad

Reputation: 5055

st.executeUpdate() either returns the row count for SQL Data Manipulation Language (DML) statements or0 for SQL statements that return nothing.

Creating a table is neither an INSERT nor an UPDATE, so it's normal to receive 0 as no row(s) were affected.

Upvotes: 7

Areeb Gillani
Areeb Gillani

Reputation: 450

I am bit doubted about your query as well, you might need to look at this

   CREATE TABLE `test1` ( contact_id INT(10),name VARCHAR(40),
   birthdate DATE,PRIMARY KEY    (contact_id));

If the update happens correctly then the value is 1, if not its 0. Moreover, it return 0 when your statement does not affect any row , for example in DDL execution it may return 0.

Upvotes: 0

dcernahoschi
dcernahoschi

Reputation: 15230

If we take a look at the Statement.executeUpdate javadoc we see that it always return 0 for DDL statements (in your case create table is a DDL statement):

Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

You can assume that the statement execution is successful if you don't get a SQLException.

Upvotes: 3

Related Questions