본문 바로가기
공부/JAVA

자바 DBConnect

by Compete 2022. 8. 3.
public static void test() {
    final String driver = "org.mariadb.jdbc.Driver";
    final String DB_IP = "localhost";
    final String DB_PORT = "3306";
    final String DB_NAME = "dbdb";
    final String DB_URL =
            "jdbc:mariadb://" + DB_IP + ":" + DB_PORT + "/" + DB_NAME;

    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        Class.forName(driver);
        conn = DriverManager.getConnection(DB_URL, "root", "1234");
        if (conn != null) {
            System.out.println("DB 접속 성공");
        }

    } catch (ClassNotFoundException e) {
        System.out.println("드라이버 로드 실패");
        e.printStackTrace();
    } catch (SQLException e) {
        System.out.println("DB 접속 실패");
        e.printStackTrace();
    }

    try {
        String sql = "select * from `game`";

        pstmt = conn.prepareStatement(sql);

        rs = pstmt.executeQuery();
        String userId = null;
        String password = null;
        String name = null;
        while (rs.next()) {
            userId = rs.getString("userid");
            password = rs.getString("userpw");
            name = rs.getString("name");
        }

        System.out.println(userId);
        System.out.println(password);
        System.out.println(name);

    } catch (SQLException e) {
        System.out.println("error: " + e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

'공부 > JAVA' 카테고리의 다른 글

Java Swing 설치 방법  (0) 2022.03.15
자바 jdk 다운 or 환경변수  (0) 2022.03.09
JAVA 1  (0) 2022.01.17

댓글