Sobes.tech
Junior

Ma'lumotlar bazasi bilan bog'lanishni qanday to'g'ri yopish mumkin?

sobes.tech AI

AIdan javob

try-with-resources blokidan foydalanish.

// Avtomatik yopiladigan resurslar e'lon qilinmoqda
try (  
    Connection connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", ""); // Connection ob'ekti olinmoqda
    Statement statement = connection.createStatement();  // Statement ob'ekti yaratilmoqda
    ResultSet resultSet = statement.executeQuery("SELECT 1") // So'rov bajarish va ResultSet olish
) {  
    // ResultSet'dan ma'lumotlar bilan ishlash yoki boshqa operatsiyalar
    while (resultSet.next()) {  
        System.out.println(resultSet.getInt(1));  
    }  
} catch (SQLException e) {  
    // Mumkin bo'lgan SQLException xatolarini boshqarish
    e.printStackTrace();  
}  

Ushbu yondashuvning afzalliklari:

  • Avtomatik yopish: (Connection, Statement, ResultSet) resurslar try blokidan chiqib ketgach, hatto xato bo'lsa ham, kafolatlangan holda yopiladi.
  • Toza kod: finally blokida close() chaqirishga ehtiyoj qolmaydi, bu boilerplate kodni kamaytiradi.
  • Xatoliklarni boshqarish: Agar resursni yopish vaqtida xato yuzaga kelsa, u try blokida yuzaga kelgan xato bilan birga yopilmaydi.

Alternativ, kamroq tavsiya etilgan usul, finally blokida ochiq yopish:

Connection connection = null;  
Statement statement = null;  
ResultSet resultSet = null;  

try {  
    connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", "");  
    statement = connection.createStatement();  
    resultSet = statement.executeQuery("SELECT 1");  
    // Ma'lumotlar bilan ishlash
    while (resultSet.next()) {  
        System.out.println(resultSet.getInt(1));  
    }  
} catch (SQLException e) {  
    e.printStackTrace();  
} finally {  
    // Resurslarni ochiqdan yopish, teskari tartibda
    if (resultSet != null) {  
        try {  
            resultSet.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
    if (statement != null) {  
        try {  
            statement.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
    if (connection != null) {  
        try {  
            connection.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }  
}  

Ushbu usul ko'proq murakkab va xatoliklar uchun moyil, ayniqsa resurslarni yopish vaqtida xatoliklar yuzaga kelganda. try-with-resources foydalanishni tavsiya qilamiz.