Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

쨍쨍

[ DB ] 작성한 채팅 프로그램에 데이터베이스 연결 본문

프로그래밍 코드/DB

[ DB ] 작성한 채팅 프로그램에 데이터베이스 연결

이선선 2023. 7. 12. 18:14

인텔리제이와 MySQL를 연동하는 방법

연동하는 이유는 따로 MySQL을 키지 않더라도 인텔리제이에서 데이터베이스를 확인할 수 있다

 

인텔리제이 화면 가장 오른 쪽에 데이터베이스 → 새로 작성 → 데이터 소스 → MySQL

(인텔리제이 유로버전이아닌 무료 버전인 Community Edition을 사용한다면 오른쪽에 데이터베이스가 나타나지 않는다.)

 

자신의 아이디, 비밀번호, 호스트와 포트를 입력한 뒤 확인이 아닌 연결 테스트를 누른다.

 

성공적으로 연결됐다

 

만든 채팅 프로그램을 실행한 뒤 사용자의 이름을 "yun"으로 설정하면

데이터베이스에도 "yun"에 데이터가 올라간다.

 

 

사용자가 메세지를 전송한다면 사용자의 닉네임과 함께 전송한 메세지가 데이터베이스에 저장된다.

 

 

< 코드 >

아래의 코드는 기존의 코드에서  데이터베이스를 연결하기 위한 MySQL 서버 주소와 데이터베이스 이름, 서버 아이디와 비밀번호를 입력해서 서버 코드를 작성한 인텔리제이와 MySQL를 연결해주는 코드를 추가해주었고, 닉네임이나 채팅내용이 내가 원하는 테이블에 저장되도록 기존에 코드에 추가적으로 수정하는 코드를 넣었다.

 

Main.java

public class Main {
    public static ArrayList<PrintWriter> OutputList;
    public static Connection connection;
    public static void main(String[] args) {
        OutputList = new ArrayList<>();
        // DB 연결 설정

        String server = "localhost"; // MySQL 서버 주소
        String database = "datalk"; // MySQL DATABASE 이름
        String user = "root"; // MySQL 서버 아이디
        String password = "0000"; // MySQL 서버 비밀번호



        // MySQL 데이터베이스에 연결하는 자바 애플리케이션 코드
        try {
            // JDBC 드라이버 로딩
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 데이터베이스 연결 - 데이터베이스 서버, 데이터베이스 이름, 사용자 이름 및 암호를 제공
            connection = DriverManager.getConnection("jdbc:mysql://" + server + "/" + database, user, password);
            System.out.println("데이터베이스가 정상적으로 연결되었습니다.");
        } catch (ClassNotFoundException | SQLException e) {
            System.err.println("데이터베이스 연결 오류: " + e.getMessage());
            e.printStackTrace();
            return;
        }

        System.out.println("서버가 시작되었습니다. 클라이언트의 연결 요청을 기다리고 있습니다...");
        try {
            ServerSocket serversocket = new ServerSocket(8000);
            while (true) {
                Socket clientsocket = serversocket.accept();
                System.out.println("[클라이언트 연결]");

                PrintWriter writer = new PrintWriter(clientsocket.getOutputStream(), true);
                OutputList.add(writer);
                System.out.println(OutputList.size());

                ClientManagerThread thread = new ClientManagerThread(clientsocket);
                thread.start();1
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } public static void addNewClientName(String clientName) {   // 클라이언트 이름을 삽입하는 메서드
        try {
            String insertQuery = "INSERT INTO client(name) VALUES (?)";
            // 클라이언트의 이름을 삽입하는 쿼리
            PreparedStatement statement = connection.prepareStatement(insertQuery);
            // PreparedStatement 생성
            statement.setString(1, clientName);
            // 첫번째 매개 변수에 클라이언트 이름을 설정

            statement.executeUpdate();
            // 데이터 삽입

            statement.close();
            // 자원 해제
        } catch (SQLException e) {
            System.err.println("데이터베이스 쿼리 실행 오류: " + e.getMessage());
            // 데이터 삽입 오류 시 에러 메세지 출력
            e.printStackTrace();
        }
    } public static void removeClientName(String clientName) {   // 클라이언트 이름을 삭제하는 메서드
        try {
            String deleteQuery = "DELETE FROM client WHERE name = ?";
            // 이름을 삭제하는 쿼리
            PreparedStatement statement = connection.prepareStatement(deleteQuery);
            // PreparedStatement 생성
            statement.setString(1, clientName);
            // // 첫 번째 매개 변수에 클라이언트 이름 설정

            statement.executeUpdate();
            // 데이터 삭제

            statement.close();
            // 자원 해제
        } catch (SQLException e) {
            System.err.println("데이터베이스 쿼리 실행 오류: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void addChatRecord(String message) {
        try {
            String insertQuery = "INSERT INTO record(talking) VALUES (?)";
            // 연결 종료 시 데이터베이스에서 클라이언트 이름을 삭제
            PreparedStatement statement = connection.prepareStatement(insertQuery);
            // 연결 종료 시 데이터베이스에서 클라이언트 이름을 삭제
            statement.setString(1, message);
            // 연결 종료 시 데이터베이스에서 클라이언트 이름을 삭제

            statement.executeUpdate();

            statement.close();
        } catch (SQLException e) {
            System.err.println("데이터베이스 쿼리 실행 오류: " + e.getMessage());
            e.printStackTrace();
        }
    }

}

 

ClientManagerThread.java

class ClientManagerThread extends Thread {
    private Socket clientSocket;
    private String clientName;
    private BufferedReader input;
    private PrintWriter output;
    public ClientManagerThread(Socket socket) {
        this.clientSocket = socket;
        try {
            input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            output = new PrintWriter(clientSocket.getOutputStream(), true);
            // 클라이언트로부터 닉네임 입력 받기
            this.clientName = input.readLine();
            // 데이터베이스에 닉네임 저장
            Main.addNewClientName(clientName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } @Override
    public void run() {
        try {
            String msg;
            while ((msg = input.readLine()) != null) {
            // 클라이언트와의 통신 처리 코드

            // 데이터베이스에 채팅 기록을 추가
            Main.addChatRecord(msg);
            }
        } catch (IOException e) {
            // 연결이 종료된 것으로 간주하고 클라이언트를 제거
            System.out.println("클라이언트 연결이 종료되었습니다.");
        } finally {
            if (clientSocket != null) {
                try {
// 연결 종료 시 데이터베이스에서 클라이언트 이름을 삭제
                    Main.removeClientName(clientName);
                    // 종료된 클라이언트의 소켓 및 입출력 스트림을 닫습니다.
                    input.close();
                    output.close();
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}