[6/27 TIL] SPRING(JDBC)

yumyeonghanยท2023๋…„ 6์›” 28์ผ
0

๐Ÿƒํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ฐฑ์—”๋“œ ๋ฐ๋ธŒ์ฝ”์Šค 4๊ธฐ ๊ต์œก๊ณผ์ •์„ ๋“ฃ๊ณ  ์ •๋ฆฌํ•œ ๊ธ€์ž…๋‹ˆ๋‹ค.๐Ÿƒ

JDBC(Java Database Connectivity)


๊ทธ๋ฆผ ์ถœ์ฒ˜

  • ์ž๋ฐ” ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜๊ณผ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๊ฐ„์˜ ์—ฐ๊ฒฐ๊ณผ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๊ธฐ ์œ„ํ•œ ์ž๋ฐ” API

JDBC Flow


๊ทธ๋ฆผ ์ถœ์ฒ˜
1. DriverManager๋ฅผ ํ†ตํ•ด์„œ ์ปจ๋„ฅ์…˜ ๊ฐ์ฒด๋ฅผ ๋ฐ›์•„์˜ด
2. Connection์„ ํ†ตํ•ด์„œ Statement๋ฅผ ๊ฐ€์ ธ์˜ด
3. Statement๋ฅผ ํ†ตํ•ด์„œ ์ฟผ๋ฆฌ๋ฅผ ์‹คํ–‰ํ•ด์„œ ResultSet์„ ๊ฐ€์ ธ์˜ค๊ฑฐ๋‚˜ update๋ฅผ ์‹คํ–‰
4. ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ฐ˜๋“œ์‹œ ์ปจ๋„ฅ์…˜์„ ์ข…๋ฃŒ

์˜ˆ์‹œ ์ฝ”๋“œ

public class JDBCCrudExample {

    // JDBC ์—ฐ๊ฒฐ ์ •๋ณด
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/sampledb";
    private static final String JDBC_USERNAME = "username";
    private static final String JDBC_PASSWORD = "password";

    public static void main(String[] args) {
        // JDBC ๋“œ๋ผ์ด๋ฒ„ ๋กœ๋“œ
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }

        // ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—ฐ๊ฒฐ
        try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD)) {
            // ๋ฐ์ดํ„ฐ ์‚ฝ์ž…
            UUID id = UUID.randomUUID();
            String name = "์œ ๋ช…ํ•œ";
            int age = 25;
            insertData(connection, id, name, age);

            // ๋ฐ์ดํ„ฐ ๊ฒ€์ƒ‰
            System.out.println("All Data:");
            retrieveData(connection);

            // ๋‹จ์ผ ํ–‰ ๊ฒ€์ƒ‰
            System.out.println("Single Row Data:");
            UUID searchId = UUID.fromString("your-id");
            UserData userData = retrieveDataById(connection, searchId);
            if (userData != null) {
                System.out.println("Data Found:");
                System.out.println("ID: " + userData.getId() + ", Name: " + userData.getName() + ", Age: " + userData.getAge());
            } else {
                System.out.println("Data Not Found");
            }

            // ๋ฐ์ดํ„ฐ ๊ฐฑ์‹ 
            String newName = "๊น€๋ช…ํ•œ";
            int newAge = 30;
            updateData(connection, id, newName, newAge);

            // ๋ฐ์ดํ„ฐ ์‚ญ์ œ
            deleteData(connection, id);

            // ์ตœ์ข… ๋ฐ์ดํ„ฐ ๊ฒ€์ƒ‰
            System.out.println("Updated Data:");
            retrieveData(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // ๋ฐ์ดํ„ฐ ์‚ฝ์ž…
    private static void insertData(Connection connection, UUID id, String name, int age) throws SQLException {
        String sql = "INSERT INTO users (id, name, age) VALUES (?, ?, ?)";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setBytes(1, toBytes(id));
            statement.setString(2, name);
            statement.setInt(3, age);
            statement.executeUpdate();
            System.out.println("Data inserted successfully.");
        }
    }

    // ๋ฐ์ดํ„ฐ ๊ฒ€์ƒ‰
    private static void retrieveData(Connection connection) throws SQLException {
        String sql = "SELECT * FROM users";
        try (Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {
            while (resultSet.next()) {
                UUID id = toUUID(resultSet.getBytes("id"));
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
            }
        }
    }
    
    // ๋‹จ์ผ ํ–‰ ๊ฒ€์ƒ‰
    private static UserData retrieveDataById(Connection connection, UUID id) throws SQLException {
        String sql = "SELECT * FROM users WHERE id = ?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setBytes(1, toBytes(id));
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    UUID userId = toUUID(resultSet.getBytes("id"));
                    String name = resultSet.getString("name");
                    int age = resultSet.getInt("age");
                    return new UserData(userId, name, age);
                }
            }
        }
        return null;
    }

    // ๋ฐ์ดํ„ฐ ๊ฐฑ์‹ 
    private static void updateData(Connection connection, UUID id, String name, int age) throws SQLException {
        String sql = "UPDATE users SET name=?, age=? WHERE id=?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, name);
            statement.setInt(2, age);
            statement.setBytes(3, toBytes(id));
            statement.executeUpdate();
            System.out.println("Data updated successfully.");
        }
    }

    // ๋ฐ์ดํ„ฐ ์‚ญ์ œ
    private static void deleteData(Connection connection, UUID id) throws SQLException {
        String sql = "DELETE FROM users WHERE id=?";
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setBytes(1, toBytes(id));
            statement.executeUpdate();
            System.out.println("Data deleted successfully.");
        }
    }

    // byte[]์„ UUID๋กœ ๋ณ€ํ™˜
    private static UUID toUUID(byte[] bytes) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
        return new UUID(byteBuffer.getLong(), byteBuffer.getLong());
    }

    // UUID๋ฅผ byte[]๋กœ ๋ณ€ํ™˜
    private static byte[] toBytes(UUID uuid) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        byteBuffer.putLong(uuid.getMostSignificantBits());
        byteBuffer.putLong(uuid.getLeastSignificantBits());
        return byteBuffer.array();
    }
}
  • sql ์ธ์ ์…˜ ๋ฐฉ์ง€ ๋ฐ ์„ฑ๋Šฅ ํ–ฅ์ƒ(์บ์‹œ ์‚ฌ์šฉ)์„ ์œ„ํ•ด Statement ๋Œ€์‹ , PreparedStatement ์‚ฌ์šฉ
  • UUID๋ฅผ ๊ธด ๋ฌธ์ž์—ด๋กœ ์ €์žฅ ํ•˜๊ธฐ๋ณด๋‹จ, byte ๋ฐฐ์—ด๋กœ ์ €์žฅํ•จ์œผ๋กœ์จ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ์„ฑ๋Šฅ๊ณผ ๊ณต๊ฐ„ ํšจ์œจ์„ฑ์„ ํ–ฅ์ƒ์‹œํ‚ด
profile
์›น ๊ฐœ๋ฐœ์— ๊ด€์‹ฌ ์žˆ์Šต๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€