Java·๏ปฟServlet·๏ปฟJSP
try-with-resource ๋ฌธ๋ฒ์ ์ฌ์ฉํ JDBC ํ๋ก๊ทธ๋๋ฐ ์์ ์ฝ๋
Leica
2020. 3. 11. 04:37
๋ฐ์ํ
try-with-resource ๋ฌธ๋ฒ์ ์ฌ์ฉํ JDBC ํ๋ก๊ทธ๋๋ฐ ์์ ์ฝ๋
try-with-resource๋ java 7 ์ด์๋ถํฐ ์ง์๋๋ฉฐ try ๋ธ๋ญ ์คํ์ด ์๋ฃ๋๋ฉด ()์์ ๋ฆฌ์์ค์ ์์์ ํด์ ํ๋ ๋ฉ์๋๋ฅผ ์๋์ผ๋ก ํธ์ถํด์ค๋ค.
String url = "jdbc:mysql://localhost:3306/myschema"; // ์์น ์ ๋ณด
String username = "user"; // ์ธ์ฆ ์ ๋ณด
String password = "1234"; // ์ธ์ฆ ์ ๋ณด
// try-with-resource
try(Connection conn = DriverManager.getConnection(url, username, password)) {
String sql = "SELECT id, username, password FROM ACCOUNT";
try(PreparedStatement pstmt = conn.prepareStatement(sql)) {
try(ResultSet rs = pstmt.executeQuery()) {
while(rs.next()) {
System.out.println(rs.getInt("id") + ", " + rs.getString("username") + ", " + rs.getString("password"));
}
}
}
}
๋ฐ์ํ