简体   繁体   English

条件SQL查询和JDBC

[英]Conditional SQL queries and JDBC

I'm writing a program utilizing JDBC that will check if a table exists and create it if it doesn't. 我正在使用JDBC编写程序,该程序将检查表是否存在,如果不存在则创建表。

I was planning to include the following: 我打算包括以下内容:

String query = (some query);
int createIfNotExists = connection.createStatement().executeUpdate(query);

But it's not allowing me to use "IF" in my SQL query. 但这不允许我在SQL查询中使用“ IF”。 Why is this? 为什么是这样? Do I need to use some different type of driver? 我需要使用其他类型的驱动程序吗? Or is IF just not allowed with JDBC? 还是仅允许JDBC使用IF? Has anyone dealt with this before, and how'd you handle it? 以前有没有人处理过,您如何处理?

DatabaseMetaData md = connection.getMetaData();  
String query = "";
boolean exist=false  

ResultSet rs = md.getTables(null, null, "table_name", null);

while (rs.next()) {
  exist = True ;
}  

if(!exist){
       query="CREATE TABLE table_name ...";
       connection.createStatement().executeUpdate(query);
}

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

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