Search code examples
javadatabasetry-catchderby

Catch table not exsist in java


I need to insert some data into a table. When program executes to insert, there may arise an error because I haven't created the table. I would like to create that table in a catch block and return to try block. So whenever the table is deleted or happens to delete, the try catch will build the table.

I have written some code for it, but it fails.

import java.sql.*;

/**
 *
 * @author JOJO
 */
public class ConnectDB {
  static Connection conn;
   static String driver = "org.apache.derby.jdbc.ClientDriver";
   static String connectionURL = "jdbc:derby://localhost:1527/Libraryprj;user=scott;password=tiger";

  public void AddBookDB(String bookName) throws SQLException {

    String createString = "CREATE TABLE BOOKLEDGER (BOOKNAME VARCHAR(50) NOT NULL)";
    try {
      Class.forName(driver);
    } catch (java.lang.ClassNotFoundException e) {
      e.printStackTrace();
    }
    try
        {
            conn = DriverManager.getConnection(connectionURL);
            Statement stmt = conn.createStatement();
            boolean execute = stmt.execute("insert into BOOKLEDGER values ('" + bookName + "')");
            stmt.close();
        }
        catch (SQLException sqlExcept)
        {
            Statement stmt = (Statement) conn.createStatement();
            stmt.executeUpdate(createString);

            sqlExcept.printStackTrace();
        }
  }
}

Solution

  • From my point of view it is better to proceed in another way(use control structure instead of try-catch), so you can test before if the table exist in this way :

    DatabaseMetaData md = conn.getMetaData();
    ResultSet rs = md.getTables(null, null, "table_name", null);
    if (!rs.next()) {
      //Table not Exist, let's create it 
    }
    //Insert data into the table ...
    

    It is a bad practice using try-catch in a similar case, try catch construct should be used only to catch exceptional situation, not in place of a control structure ...