首页 > 解决方案 > 为什么我的方法不是我的方法删除存在的表?

问题描述

我有检查表是否存在的方法,如果存在,它会删除它然后重新创建它。否则,它会创建表。它是使用这种方法完成的,因为我必须为我的作业这样做。

我有一个打印语句,告诉我该表确实存在(它打印如果在里面if statement检查它是否存在)。然后我收到一条错误消息:

无法创建表 org.postgresql.util.PSQLException:错误:在“$1”或附近出现语法错误位置:12

方法:

public static void createTable(Connection conn, String name, String description) {
   PreparedStatement pst = nul;
    Statement st = null;

    String SQL = "drop table ?; create table ?";

    try {
        if (tableExist(conn, name)) {
            System.out.println("Works");
            pst = conn.prepareStatement(SQL);
            pst.setString(1, name);
            pst.setString(2, description);
            int update = pst.executeUpdate();
        } else {
            st = conn.createStatement();
            st.execute("create table " + description);
        }
    } catch (SQLException e) {
        System.out.println("Could not create table(s) " + e);
    }
}

有什么我做错了吗?

标签: javasqlpostgresqljdbc

解决方案


这里有两件事:

  • 利用drop table if exists
  • executeupdate是为了一个陈述。
  • 您不能将标识符作为参数传递,因此您必须修改查询字符串。

所以,发出两条语句:

"drop table if exists <table name>"
"create table . . . "

推荐阅读