Postgresql: how to create table only if it does not already exist?

后端 未结 10 927
不思量自难忘°
不思量自难忘° 2021-01-31 08:04

In Postgresql, how can I do a condition to create a table only if it does not already exist?

Code example appreciated.

10条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 08:09

    What I used to check whether or not a table exists (Java & PostgreSQL) prior to creating it. I hope this helps someone. The create table portion is not implemented here, just the check to see if a table already exists. Pass in a connection to the database and the tableName and it should return whether or not the table exists.

    public boolean SQLTableExists(Connection connection, String tableName) {
        boolean exists = false;
    
        try {
            Statement stmt = connection.createStatement();
            String sqlText = "SELECT tables.table_name FROM information_schema.tables WHERE table_name = '" + tableName + "'";    
            ResultSet rs = stmt.executeQuery(sqlText);
    
            if (rs != null) {
                while (rs.next()) {
                    if (rs.getString(1).equalsIgnoreCase(tableName)) {
                        System.out.println("Table: " + tableName + " already exists!");
                        exists = true;
                    } else { 
                        System.out.println("Table: " + tableName + " does not appear to exist.");
                        exists = false;
                    }
    
                }
            }
    
        } catch (SQLException sqlex) {
            sqlex.printStackTrace();
        }
        return exists;
    }
    

提交回复
热议问题