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

后端 未结 10 951
不思量自难忘°
不思量自难忘° 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条回答
  •  花落未央
    2021-01-31 08:19

    Try running a query on the table. If it throws an exception then catch the exception and create a new table.

    try {
        int a =  db.queryForInt("SELECT COUNT(*) FROM USERS;");
    }
    catch (Exception e) {
        System.out.print(e.toString());
        db.update("CREATE TABLE USERS (" +
                    "id SERIAL," +
                    "PRIMARY KEY(id)," +
                    "name varchar(30) NOT NULL," +
                    "email varchar(30) NOT NULL," +
                    "username varchar(30) NOT NULL," +
                    "password varchar(30) NOT NULL" +
                    ");");
    }
    return db;
    

提交回复
热议问题