简体   繁体   English

Postgresql:如果表格尚不存在,如何创建表格?

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

In Postgresql, how can I do a condition to create a table only if it does not already exist? 在Postgresql中,如果表格尚不存在,我怎么能创建一个条件呢?

Code example appreciated. 代码示例赞赏。

I'm not sure when it was added, but for the sake of completeness I'd like to point out that in version 9.1 (maybe before) IF NOT EXISTS can be used. 我不确定它何时被添加,但为了完整起见,我想指出在版本9.1(可能之前)中, IF NOT EXISTS IF NOT EXISTS will only create the table if it doesn't exist already. IF NOT EXISTS只会创建表,如果它还不存在。

Example: 例:

CREATE TABLE IF NOT EXISTS users.vip
(
  id integer
)

This will create a table named vip in the schema users if the table doesn't exist. 如果表不存在,这将在模式users创建名为vip的表。

Source 资源

create or replace function update_the_db() returns void as
$$
begin

    if not exists(select * from information_schema.tables 
        where 
            table_catalog = CURRENT_CATALOG and table_schema = CURRENT_SCHEMA
            and table_name = 'your_table_name_here') then

        create table your_table_name_here
        (
            the_id int not null,
            name text
        );

    end if;

end;
$$
language 'plpgsql';

select update_the_db();
drop function update_the_db();

Just create the table and don't worry about whether it exists. 只需创建表,不要担心它是否存在。 If it doesn't exist it will be created; 如果它不存在,它将被创建; if it does exist the table won't be modified. 如果确实存在,则不会修改表。 You can always check the return value of your SQL query to see whether the table existed or not when you executed the create statement. 您始终可以检查SQL查询的返回值,以查看执行create语句时表是否存在。

I think to check the pg_class table perhaps help you, something like that: 我想检查一下pg_class表可能对你有帮助,比如说:

SELECT COUNT (relname) as a FROM pg_class WHERE relname = 'mytable'

if a = 0 then (CREATE IT)

Regards. 问候。

This is an old question. 这是一个老问题。 I'm only bringing back to suggest another answer. 我只是带回来提出另一个答案。 Note: other better answers already exist, this is just for educational purposes . 注意: 其他更好的答案已经存在,这仅用于教育目的

The easiest way is to do what others have said; 最简单的方法是做别人说的话; perform the CREATE TABLE if you want to keep the existing data, or perform a DROP IF EXISTS and then a CREATE TABLE, if you want a freshly created table. 如果要保留现有数据,请执行CREATE TABLE;如果需要新创建的表,则执行DROP IF EXISTS,然后执行CREATE TABLE。

Another alternative is to query the system table for its existence and proceed from there. 另一种方法是查询系统表的存在并从那里继续。

SELECT true FROM pg_tables WHERE tablename = <table> [AND schemaname = <schema>];

In use: 正在使用:

-- schema independent:
SELECT true FROM pg_tables WHERE tablename = 'foo';

-- schema dependent:
SELECT true FROM pg_tables WHERE tablename = 'foo' AND schemaname = 'bar';

If it matches you'll have a true value, otherwise it should return an empty dataset. 如果它匹配,你将有一个真值,否则它应该返回一个空数据集。 You can use that value to determine if you need to perform a CREATE TABLE. 您可以使用该值来确定是否需要执行CREATE TABLE。

The best answer has been given by Skalli if you're running Postgresql 9.1+. 如果您正在运行Postgresql 9.1+,Skalli会给出最佳答案。

If like me you need to do that with Postgresql 8.4, you can use a function with a 'duplicate_table' exception catch. 如果像我一样你需要使用Postgresql 8.4,你可以使用带有'duplicate_table'异常catch的函数。

This will ignore the generated error when the table exists and keep generating other errors. 当表存在时,这将忽略生成的错误并继续生成其他错误。

Here is an example working on Postgresql 8.4.10 : 以下是Postgresql 8.4.10的一个示例:

CREATE FUNCTION create_table() RETURNS VOID AS
$$
BEGIN
    CREATE TABLE my_table_name(my_column INT);
EXCEPTION WHEN duplicate_table THEN
    -- Do nothing
END;
$$
LANGUAGE plpgsql;

What I used to check whether or not a table exists (Java & PostgreSQL) prior to creating it. 我在创建表之前用来检查表是否存在(Java和PostgreSQL)。 I hope this helps someone. 我希望这可以帮助别人。 The create table portion is not implemented here, just the check to see if a table already exists. 此处未实现create table部分,只是检查表是否已存在。 Pass in a connection to the database and the tableName and it should return whether or not the table exists. 传递与数据库和tableName的连接,它应返回表是否存在。

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;
}

The easiest answer is : 最简单的答案是:

catch{

#create table here

}

This creates a table if not exists and produces an error if exists. 如果不存在,则创建表,如果存在则生成错误。 And the error is caught. 并且错误被抓住了。

http://www.postgresql.org/docs/8.2/static/sql-droptable.html

DROP TABLE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM