Question

In my spring project, I have this code to create the database the application will use:

        int result = stmt.executeUpdate("CREATE DATABASE horario WITH OWNER "+usuario+";");
        System.out.println("result = "+result);
        if(result > 0) {
            System.out.println("calling_create_tables");
            create_tables(maquina, usuario, senha);
            rs.close();
            stmt.close();
            conn.close();
            return true;
        }

The problem is, despite the database being created normally, the variable result is always receiving the value 0, what cause the non execution of code inside the if.

Anyone knows why this happening?

ps.: the full code for the class is this: https://github.com/klebermo/webapp_horario_livre/blob/master/src/com/horariolivre/service/InstallService.java

Was it helpful?

Solution

the variable result is always receiving the value 0, what cause the non execution of code inside the if.

From Statement#executeUpdate javadoc:

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

In your case, you're executing a DDL statement that returns nothing, so your output will always be 0. This doesn't mean the statement didn't get executed, it is just how the underlying implementation should behave (and it's ok).

By the way, in JDBC, you should not append semicolon to your SQL statements, so remove the semicolon at the end of your statement:

//no semicolon at the end
int result = stmt.executeUpdate("CREATE DATABASE horario WITH OWNER "+ usuario);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top