建立 user 數據庫git
建立 teacher 數據庫github
teacher表的user_id列與user表的id列創建一對多鏈接,user_id做爲外鍵。sql
/** * 添加數據 */ @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); } }
/** * 一對多查詢 * 根據主表查詢從表 */ @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); } } }
項目代碼:https://github.com/wjw1014/JavaMysqlStudy/tree/master/ConnSQL (小白操做,僅供參考!)數據庫