【问题标题】:SQLexception when table exists表存在时的SQL异常
【发布时间】:2012-05-26 00:15:47
【问题描述】:

我想用JDBC输入一个命令来创建一个表,但是在第一次编译后,当表已经生成时,下一个都会抛出异常。我不明白这怎么可能,因为我已经把 [IF NOT EXISTS] 术语放在那里,所以应该没有 SQL 错误。

public class Test 
{
    public static void main(String[] args) 
    {
        try
        {
            Connection conn = BazaDanych.Polacz();
            Statement stat = conn.createStatement();

           String command = "CREATE TABLE [IF NOT EXISTS] testowatabela2 (id INTEGER, wartosc DOUBLE PRECISION);";

            stat.execute(command);
        }
        catch(SQLException e)
        {
            System.out.println("SQL Exception in Test");
        }
    }
}

【问题讨论】:

  • catch(SQLException e) { 更改为 catch(SQLException e) { e.printStackTrace(); 并复制/粘贴输出。
  • 有些数据库不支持 IF NOT EXISTS 结构。
  • IF NOT EXISTS 应该放在方括号中吗?
  • org.postgresql.util.PSQLException:错误:错误在或接近“[”位置:14 在 org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102) 在 org .postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835) 在 org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) 在 org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java :500) 在 org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags

标签: java sql database postgresql jdbc


【解决方案1】:

可能,包含IF NOT EXISTS 子句的括号逐字逐句来自文档: http://www.postgresql.org/docs/9.1/static/sql-createtable.html

但它们不能出现在实际的CREATE TABLE 语句中,因为括号表示该子句是可选的

要考虑的另一件事是IF NOT EXISTS 是 PostgreSQL 9.1 的一个新特性,所以它会在旧版本上失败。如果您不确定您使用的版本,请在 SQL 中运行:select version()

【讨论】:

    【解决方案2】:

    试试

    IF NOT EXISTS (SELECT 1 
               FROM sysobjects 
               WHERE xtype='u' AND name='testowatabela2')
        CREATE TABLE testowatabela2 (id INTEGER, wartosc DOUBLE PRECISION)
    

    编辑

    只需留下[IF NOT EXISTS] 部分。根据this answer,表是否存在并不重要。

    【讨论】:

    • @Noran:这种语法在 PostgreSQL 中不起作用,所以不要费心尝试(juergen 在你的问题被 PostgreSQL 标记之前添加它)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多