java - 为什么我的方法不是我的方法删除存在的表?
问题描述
我有检查表是否存在的方法,如果存在,它会删除它然后重新创建它。否则,它会创建表。它是使用这种方法完成的,因为我必须为我的作业这样做。
我有一个打印语句,告诉我该表确实存在(它打印如果在里面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);
}
}
有什么我做错了吗?
解决方案
这里有两件事:
- 利用
drop table if exists
executeupdate
是为了一个陈述。- 您不能将标识符作为参数传递,因此您必须修改查询字符串。
所以,发出两条语句:
"drop table if exists <table name>"
"create table . . . "
推荐阅读
- scala - Spark如何传递Scala对象进行映射转换
- android - 如何将托管在我的服务器上的 OpenMapTiles 用于 android kotlin
- typescript - 如何在并发测试中获得独特的玩笑间谍?
- android - 使用 Braintree SDK 在 Android 中支付 PayPal
- python - 使用多个单词作为不和谐前缀,中间有空格
- c# - 最小起订量设置使用构造函数参数获取 dbContext
- javascript - 如何从 JS 数组中过滤数据并创建另一个 JS 数组
- python - Bot 不会与 VC 断开连接,但不会引发任何错误 [Discord.py]
- macos - 如何使用 Docker Desktop 在 MacOS 上的 docker 容器中连接和使用摄像头
- c++ - c++比较器排序使用辅助数组