๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java·๏ปฟServlet·๏ปฟJSP

try-with-resource ๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•œ JDBC ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์˜ˆ์ œ ์ฝ”๋“œ

by Leica 2020. 3. 11.
๋ฐ˜์‘ํ˜•

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"));
            }
        }
    }
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€