>  기사  >  Java  >  Java에서 데이터베이스를 쿼리하는 방법

Java에서 데이터베이스를 쿼리하는 방법

coldplay.xixi
coldplay.xixi원래의
2020-08-17 13:38:2210895검색

Java에서 데이터베이스를 쿼리하는 방법: 먼저 사용자 및 교사 데이터베이스를 만든 다음 교사 테이블의 [user_id] 열과 사용자 테이블의 id 열 사이에 일대다 연결을 설정합니다. 조건에 따라 사용자 데이터 테이블 및 사용자 쿼리 데이터베이스 데이터를 기반으로 최종적으로 마스터 테이블을 기반으로 슬레이브 테이블 데이터를 쿼리합니다.

Java에서 데이터베이스를 쿼리하는 방법

【관련 학습 권장사항: java 기본 튜토리얼

Java에서 데이터베이스를 쿼리하는 방법:

1. 데이터베이스 생성

사용자 데이터베이스 생성

Java에서 데이터베이스를 쿼리하는 방법

만들기 교사 데이터베이스

Java에서 데이터베이스를 쿼리하는 방법

교사 테이블의 user_id 열은 사용자 테이블의 id 열과 일대다 연결을 설정하고 user_id가 외래 키로 사용됩니다.

Java에서 데이터베이스를 쿼리하는 방법

2. 데이터베이스 쿼리를 위한 Java 프로그래밍

사용자 데이터 테이블에 데이터 추가

    /**
     * 添加数据
     */
    @Test
    public void addData() {
        Connection connection = null;
        PreparedStatement pstmt =null;
        try {
            connection = JDBCUtils_V3.getConnection();
            String sql = "insert into user values(null,?,?)";
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, "wangxuan");
            pstmt.setString(2, "741852");
            int row = pstmt.executeUpdate();
            if (row>0) {
                System.out.println("数据添加成功!");
            }else {
                System.out.println("数据添加失败!");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtils_V3.release(connection, pstmt, null);
        }
    }

조건에 따라 사용자 데이터베이스 데이터 쿼리

    /**
     * 按照条件查询数据
     */
    @Test
    public void selectTest() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs =null;
        try {
            conn = JDBCUtils_V3.getConnection();
            String sql = "select * from user where password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "123456");
            rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString(1)+"----"+rs.getString(2)+"---"+rs.getString(3));
            }
//            System.out.println(rs);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtils_V3.release(conn, pstmt, rs);
        }
    }

일대다 쿼리/슬레이브 테이블 교사 쿼리 데이터는 메인 테이블 user

    /**
     * 一对多查询
     * 根据主表查询从表
     */
    @Test
    public void selectOnetoMore() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils_V3.getConnection();
//            String sql = "select * from teacher where user_id = (select id from user where username =?) ";
            String sql = "select * from user,teacher where user.id = teacher.user_id ";
            pstmt = conn.prepareStatement(sql);
//            pstmt.setString(1, "wangxuan");
            rs = pstmt.executeQuery();
            while (rs.next()) {
//                System.out.println(rs.getString(1)+"----"+rs.getString(2)+"---"+rs.getString(3)+"---"+rs.getString(4));
                System.out.println(rs.getString(1)+"----"+rs.getString(2)+"---"+rs.getString(3)+"---"+rs.getString(4)+"----"+rs.getString(5)+"----"+rs.getString(6)+"----"+rs.getString(7));
            }
            System.out.println("查询完成");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtils_V3.release(conn, pstmt, rs);
        }
    }

일대다 쿼리/슬레이브 테이블 기반 마스터 테이블 쿼리

    /**
     * 一对多查询
     * 根据从表查询主表数据
     */
    @Test
    public void selectMoretoOne() {
        Connection connection = null;
        PreparedStatement pstmtPreparedStatement = null;
        ResultSet rSet =null;
        try {
            connection = JDBCUtils_V3.getConnection();
            String sql = "select * from user where id = (select user_id from teacher where teacher=?)";
            pstmtPreparedStatement = connection.prepareStatement(sql);
            pstmtPreparedStatement.setString(1, "钱田");
            rSet = pstmtPreparedStatement.executeQuery();
            while (rSet.next()) {
                System.out.println(rSet.getString(1)+"----"+rSet.getString(2)+"---"+rSet.getString(3));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtils_V3.release(connection, pstmtPreparedStatement, rSet);
        }
    }
}

관련 권장 사항: 프로그래밍 비디오 코스

위 내용은 Java에서 데이터베이스를 쿼리하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.