我是Java的新手,无法理解try / catch在以下代码中的位置。这个项目还有很多,但这是问题领域
Statement stmt = con.createStatement();
String query = "SELECT FirstName, LastName FROM Customer";
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
String ln = rs.getString("FirstName");
String ln1 = rs.getString("LastName");
System.out.println(ln + " " + ln1);
}
答案 0 :(得分:1)
如果您使用的是Java 7+,则可以使用try-with-resources。
文档链接中的一个示例:
public static void viewTable(Connection con) throws SQLException {
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + ", " + supplierID + ", " +
price + ", " + sales + ", " + total);
}
} catch (SQLException e) {
JDBCTutorialUtilities.printSQLException(e);
}
}
答案 1 :(得分:0)
只要调用可以抛出异常的方法,就会使用Try-catch。在你的情况下:
ResultSet rs = null;
try {
Statement stmt = con.createStatement();
String query = "SELECT FirstName, LastName FROM Customer";
rs = stmt.executeQuery(query);
catch(Exception e){
e.printStackTrace();
}
例如。
答案 2 :(得分:0)
可以在ResultSet的文档中找到try / catch的需要。我假设executeQuery在输入SQL查询中抛出了语法错误的异常。不确定,但getString也可能抛出异常。
如果executeQuery需要一个......
@echo off
setlocal enabledelayedexpansion
set count=0
for /f %%D in ('wmic volume get DriveLetter^, Label ^| find /i "Video"') do (
set /a count+=1
set drive!count!=%%D
)
echo %count% drives found:
set drive 2>nul
if %count% gtr 4 echo too much...