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

后端 未结 4 1839
醉梦人生
醉梦人生 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:36

    Knowing that you can practically select a column from a table using the following SQL statement (in MySQL):

    show columns from TABLE_NAME where field = 'FIELD_NAME';
    

    You could do something like:

    ...
    PreparedStatement preparedStatement =
      connection.prepareStatement(
        "show columns from [TABLE_NAME] where field = ?");
    preparedStatement.setString(1, columName);
    
    ResultSet resultSet = preparedStatement.executeQuery();
    
    if (resultSet.next()) {
        System.out.println("column exists!");
    } else {
        System.out.println("column doesn't exists!");
    }
    ...
    

提交回复
热议问题