在我的自动化脚本中,必须从SQL中提取一个数据,才能在特定条件下填写表单。因此,我运行SQL查询,并将第一个数据(从第0个位置开始(存储在字符串中,如下所示:
String name = (String) DBUtil.executeQuery("<QUERY>", new Object[0]).get(0).get("<COLUMN_Name>");
我正在做这一类,其中编写了测试脚本。下面是在另一个类DBUtil中编写的executeQuery方法,它对所有查询都很好。
我面临的问题是,查询没有获取任何结果,并且字符串名称中没有存储任何内容。在这种情况下,在运行测试脚本时,它会抛出IndexOutofBounException,因为没有提取任何结果。有人能就如何处理这个部分提出建议吗?
这取决于异常发生的位置。您可以尝试使用SELECT AS
将查询调整为结果中始终有一列,查看这两个查询的不同结果:
select newid();
select newid() as newid;
另一种方法是使用try/catch块:
String name = null;
try {
name = (String) DBUtil.executeQuery("<QUERY>", new Object[0]).get(0).get("<COLUMN_Name>");
}
catch (IndexOutofBounException indexOutofBounException) {
}
更新:
或者你可以离开DBUtil.executeQuery
并使用这个:
public static List<String> getQueryResults(Connection connection, String query, String key) {
List<String> results = new ArrayList<String>();
try {
Statement statement = connection.createStatement();
statement.setQueryTimeout(60);
ResultSet result = statement.executeQuery(query);
while (result.next()) {
results.add(result.getString(key));
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
用法示例:
public static Boolean databaseExists(Connection connection, String dbName) {
List<String> dbNames = getQueryResults(connection, "SELECT name FROM sys.databases", "name");
if (dbNames.contains(dbName)) {
return true;
}
else {
return false;
}
}
或类似:
public static Map<String, String> mapQueryResult(Connection connection, String query, String key, String value) {
Map<String, String> map = new HashMap<String, String>();
ResultSet result = null;
try {
result = connection.createStatement().executeQuery(query);
while (result.next()) {
map.put(result.getString(key), result.getString(value));
}
} catch (SQLException e) {
e.printStackTrace();
}
return map;
}
用法示例:
public static String getBackupLogicalName(Connection connection, File backupFile) {
String origin = null;
String query = "RESTORE FILELISTONLY FROM DISK = N'" + backupFile.getAbsolutePath() + "' WITH NOUNLOAD;";
Map<String, String> results = mapQueryResult(connection, query, "FileGroupName", "LogicalName");
if (results.size() > 0) {
origin = results.get("PRIMARY");
}
return origin;
}