How to check if a table or a column exists in a database?

后端 未结 4 1837
醉梦人生
醉梦人生 2020-12-09 11:18

I am trying to make simple java code that will check if a table and/or a column exists in a MySQL DB. Should I use Java code to do the checking or make a SQL query string an

4条回答
  •  攒了一身酷
    2020-12-09 11:47

    To check if a table exist you can use DatabaseMetaData in this way :

    DatabaseMetaData md = connection.getMetaData();
    ResultSet rs = md.getTables(null, null, "table_name", null);
    if (rs.next()) {
      //Table Exist
    }
    

    And to check if a column exist you can use it in a similar way :

    DatabaseMetaData md = connection.getMetaData();
    ResultSet rs = md.getColumns(null, null, "table_name", "column_name");
     if (rs.next()) {
          //Column in table exist
        }
    

提交回复
热议问题