Search code examples
javamysqljdbcjavadb

Want to add validation to my code , if table doesn't exist it should create the new table in java


Please don't mark my question as duplicate I tried other solutions but they are'nt working. I am trying to place a validation that , if table doesn't exist then create.

void checkCreateMeth()
    {
        try{
        System.out.println("Implementing the functionality of create table if not exist or not.");
        Class.forName(JDBC_Driver);
        con=DriverManager.getConnection(DB_URL, user, pass);
        stmt=con.createStatement();
        String sql="CREATE TABLE IF NOT EXISTS VGRWER(name varchar(10),stream varchar(10))";
            int rs=stmt.executeUpdate(sql);
            System.out.println("Value of rs is="+rs);
        }catch(Exception e)
        {
            e.printStackTrace();                         
        }
    }
  1. Firstly I used exexuteQuery() it gave error "Can not issue data manipulation statements with executeQuery()"

  2. Secondly , I tried executeUpdate() , it returned "0" when table was existing. It returned same value when I provided the table_name which was not existing.


Solution

  • From the javadocs :

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

    https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)

    This means that your DDL statement is always going to return 0 irrespective of whether the table exists or not.