Java Ma'lumotlar bazasi

Java dasturlash tilida ma’lumotlar bazasiga ulanish va SQL so’rovlarni amalga oshirish uchun JDBC (Java Database Connectivity) deb nomlangan kutubxona (API) dan foydalaniladi. Ma’lumotlar bazasi bilan ishlash uchun SQL bo’yicha boshlang’ich bilimlar bo’lishi kerak. Quyidagi havola orqali SQL darsligimizni topishingiz mumkin: https://uzbekdevs.uz/darsliklar/sql

JDBC dan foydalanish uchun 4 xil driver mavjud:

  • JDBC-ODBC Bridge Driver
  • Native Driver
  • Network Protocol Driver
  • Thin Driver

java.sql papkasi JDBC ning barcha class va interfeyslarini o’z ichiga olgan. Quyidagilar ulardan ba’zilari:

  • Driver interface
  • Connection interface
  • Statement interface
  • PreparedStatement interface
  • CallableStatement interface
  • ResultSet interface
  • DriverManager class
  • Blob class
  • Clob class
  • Types class

JDBC orqali ma’lumotlar bazasiga ulanib, so’rovlar yuborish uchun quyidagi 5 qadamlarni bajarish kerak:

  • Driver classini ro’yxatdan o’tkazish
  • Connection (aloqani) yaratish
  • Statement (ifodani) yaratish
  • So’rovlarni yuborish
  • Connectionni (aloqani) yopish

Keling endi yuqoridagilarni batafsil ko’rib chiqamiz.

Driverni ro’yxatdan o’tkazish uchun Class nomli classning forName() metodidan foydalaniladi:

Class.forName("oracle.jdbc.driver.OracleDriver");  

Connection ya’ni ma’lumotlar bazasiga ulanishni amalga oshirib beradigan obyekt yaratish uchun DriverManager classining getConnection() metodida qo’llaniladi:

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");

So’rovlarni jo’natish uchun foydalaniladigan statement obyekti Connection interfeysining createStatement() metodidan foydalaniladi va u Statement obyektini qaytaradi:

Statement stmt=con.createStatement();  

Statement interfeysining executeQuery() metodi esa ma’lumotlar bazasiga SQL so’rov jo’natish uchun ishlatiladi. Natija ResultSet obyekti sifatida qaytadi va u ma’lumotlar bazasidagi barcha ma’lumotlarni olish imkoniyatga ega. Quyida misol keltiramiz:

ResultSet rs=stmt.executeQuery("select * from users");  

Ma’lumotlar bazasiga ulanishni yakunlash uchun Connection interfeysining close() metodidan foydalanamiz:

con.close();  

Keling endi MySQL serveridagi ma’lumotlar bazasiga ulanishga doir kodlarni ko’rib chiqamiz. Buning uchun quyidagi nuqtalarga e’tibor berishimiz kerak:

  • MySQL ma’lumotlar bazasiga ulanish uchun com.mysql.jdbc.Driver driveridan foydalaniladi.
  • jdbc:mysql://localhost:3306/malumotlarbazasinomi kabi URL dan foydalaniladi. Bunda “jdbc” JDBC APIni, “mysql” MySQL serverni, “localhost” server nomini, “3306” portni va “malumotlarbazasinomi” ma’lumotlar bazasi nomini anglatadi.
  • Username bu ma’lumotlar bazasi egasi nomi. Default holatda MySQL da root bo’ladi.
  • Password ma’lumotlar bazasiga ulanish uchun maxfiy parol.

Kod yozishdan avval MySQL serverida “demobaza” nomi bilan ma’lumotlar bazasi va unda “users” nomli jadval yaratamiz.

Endi JDBC yordamida CRUD operatsiyalarini bajarishni ko’rib chiqamiz:

Ma’lumot qo’shish operatsiyasi

import java.sql.*;
 
public class JDBCTest {
    public static void main(String[] args) {
        User user = new User(5, "User", "[email protected]");
        Connection connection = null;
        Statement statement = null;
 
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demobaza", "root", "password");
            statement = connection.createStatement();
 
            String SQL = "INSERT INTO students(id, name, email, gender, status, city) " +
                    "VALUES( " + user.getId() + ", '" + user.getName() + "', '" + user.getEmail() + "', '"
                    + user.getGender() + "', " + user.isStatus() + ",'" + user.getCity() + "'')";
 
            int num = statement.executeUpdate(SQL);
 
            System.out.println(num + " foydalanuvchi qo’shildi");
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
}

Ma’lumotni olish operatsiyasi

import java.sql.*;
 
public class JDBCTest {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
 
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demobaza", "root", "password");
            statement = connection.createStatement();
            resultSet = statement.executeQuery("SELECT * FROM users");
 
            while (resultSet.next()) {
                System.out.print(resultSet.getInt("id"));
                System.out.print(resultSet.getString("name"));
                System.out.print(resultSet.getString("email"));
            }
             
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
}

Ma’lumotni yangilash operatsiyasi

import java.sql.*;
 
public class JDBCTest {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
 
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demobaza", "root", "password");
            statement = connection.createStatement();
            int num = statement.executeUpdate("UPDATE users SET name='User1', email='[email protected]' WHERE id=1");
            System.out.println(num + " foydalanuvchi ma’lumotlari yangilandi.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
}

Ma’lumotlarni o’chirish operatsiyasi

import java.sql.*;
public class JDBCTest {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demobaza", "root", "password");            statement = connection.createStatement();
            int num = statement.executeUpdate("DELETE FROM students WHERE id=1");
            System.out.println(num + " foydalanuvchi ma’lumotlari o’chirildi.");
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
}