使用 JdbcTemplate 和 T-SQL 检查 SQL 数据库中是否存在 table
Check if a table exist in the SQL DB using JdbcTemplate and T-SQL
我正在努力检查数据库中是否存在 table。我目前所做的如下:
public boolean isTableExist(String tableName) {
JdbcTemplate jdbc = getJdbcTemplate();
String query =
"IF (OBJECT_ID(?) IS NOT NULL ) "
+ "BEGIN "
+ " PRINT 1 "
+ " RETURN "
+ "END "
+ "ELSE "
+ "BEGIN "
+ " PRINT 0 "
+ " RETURN "
+ "END";
Integer result = jdbc.queryForObject(query, Integer.class, tableName);
return result == 1 ? true : false;
}
输出(错误):
PreparedStatementCallback; uncategorized SQLException for SQL [IF
(OBJECT_ID(?) IS NOT NULL ) BEGIN PRINT 1 RETURN END ELSE BEGIN
PRINT 0 RETURN END]; SQL state [null]; error code [0]; The statement
did not return a result set.; nested exception is
com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not
return a result set.
您也可以运行这样的查询:
select count(*)
from information_schema.tables
where table_name = 'yourtablename'
-- optionally this too
-- and table_schema = 'dbo';
如果得到零,则 table 不存在。
根据 的回答,似乎您在存储查询后可能必须使用类似的东西
jdbc.queryForObject(
"select count(*) from information_schema.tables where table_name = ?"
, new Object[] { tableName }
, Integer.class
);
更新:
借助此 post 问题已得到解决,基于上述信息的最终解决方案是:
String query =
"select count(*) "
+ "from information_schema.tables "
+ "where table_name = ? and table_schema = 'dbo'";
Integer result = jdbc.queryForObject(query, Integer.class, tableName);
我正在努力检查数据库中是否存在 table。我目前所做的如下:
public boolean isTableExist(String tableName) {
JdbcTemplate jdbc = getJdbcTemplate();
String query =
"IF (OBJECT_ID(?) IS NOT NULL ) "
+ "BEGIN "
+ " PRINT 1 "
+ " RETURN "
+ "END "
+ "ELSE "
+ "BEGIN "
+ " PRINT 0 "
+ " RETURN "
+ "END";
Integer result = jdbc.queryForObject(query, Integer.class, tableName);
return result == 1 ? true : false;
}
输出(错误):
PreparedStatementCallback; uncategorized SQLException for SQL [IF (OBJECT_ID(?) IS NOT NULL ) BEGIN PRINT 1 RETURN END ELSE BEGIN
PRINT 0 RETURN END]; SQL state [null]; error code [0]; The statement did not return a result set.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
您也可以运行这样的查询:
select count(*)
from information_schema.tables
where table_name = 'yourtablename'
-- optionally this too
-- and table_schema = 'dbo';
如果得到零,则 table 不存在。
根据
jdbc.queryForObject(
"select count(*) from information_schema.tables where table_name = ?"
, new Object[] { tableName }
, Integer.class
);
更新: 借助此 post 问题已得到解决,基于上述信息的最终解决方案是:
String query =
"select count(*) "
+ "from information_schema.tables "
+ "where table_name = ? and table_schema = 'dbo'";
Integer result = jdbc.queryForObject(query, Integer.class, tableName);