0

It is as the title suggest. I want to create a java program in which I will be able to create tables and modify data using Oracle Base/JDBC and I want it to have multiple usage. Sadly when I google "oracle create table", there are only programs which are useless after one usage.

For now I tried something like that, but it is not working as program says the table does not exist.

try{
    boolean tableExists;
    Statement statement = createStatement();
    String sql1 = "SELECT * FROM tableName";

    While(statement.execute(sql1)){
        tableExists = true;
        break;
    }

    while(tableExists= false){
        String sql2 = "CREATE TABLE tableName(id integer not null, name char(10) not null)";
        statement.execute(sql2);
        tableExists = true;
        break;
    }
} catch (Exception e) {
    e.printStackTrace();
    return;
}
Calos
  • 1,783
  • 19
  • 28

1 Answers1

0

First , you are unnecessary using while statements, its basically a case of if.

Secondly, your code has Java syntax level problems like statement , while(tableExists= false) so it seems you are new to Java too.

Thirdly, if table doesn't exist , your first call statement.execute(sql1) will throw an Exception and control will directly go to catch block & your second statement will not be executed. So I would revise your code to something like below.

Also, note that second query needs to be executeUpdate & not execute ...Refer here

try{
    boolean tableExists = false;
    Statement statement = createStatement();
    String sql1 = "SELECT * FROM tableName";
    if(statement.execute(sql1)){
        tableExists = true;
    }

    // do other things 

    return ;

} catch (Exception e) {
    e.printStackTrace();
    if(!tableExists){
        String sql2 = "CREATE TABLE tableName(id integer not null, name char(10) not null)";
        statement.executeUpdate(sql2);
        tableExists = true;
    }
    return;
}

Note that this is still not a very good & fool proof code since control can go to catch block for other errors too & not only table exist issue.Table not existing is one of many reasons that an exception can be thrown & you might need to examine trace message to exactly know if table not existing is the real issue or can use something like EXISTS in SQL to try creating table only if it doesn't exist.

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98