1、核心代码块
@Test public void testConn() throws Exception { // 1. 加载数据库的连接驱动 // Driver=com.mysql.jdbc.Driver Class.forName("com.mysql.jdbc.Driver"); // 2. 造桥,建立连接 // url = jdbc:mysql://localhost:3306/数据名称 String url = "jdbc:mysql://localhost:3306/xc"; String user = "root"; String password = "root"; Connection conn = DriverManager.getConnection(url, user, password); // 3.获取传送指令(SQL)的接口对象 Statement stmt = conn.createStatement(); // stmt.executeQuery(sql); // 当你要做查询的时候,用query // stmt.executeUpdate(sql); // insert update delete 使用update String sql = " SELECT * FROM user "; // 4. 得到结果集,然后处理结果集 ResultSet rs = stmt.executeQuery(sql); // rs.next() 返回true表示rs结果有数据 false表示没有数据了 while (rs.next()) { // 获取单个的数据,一个一个的列 int studentNo = rs.getInt("id");// String loginPwd = rs.getString(2); String studentName = rs.getString("name"); //String sex = rs.getString("sex"); System.out.println( "studentNo=" + studentNo + " loginPwd=" + loginPwd + " studentName=" +studentName); } // 5.拆桥 ,释放资源 rs.close(); stmt.close(); conn.close(); }
2、crud
// 1. 新增 @Test public void testInsert() throws Exception { String sql = " INSERT INTO DOG VALUES(NULL,‘拉布拉多‘, 80, 100, ‘大型犬‘) "; try { this.insertOrUpdateOrDelete(sql ); } catch (Exception e) { e.printStackTrace(); } } // 2. 修改 @Test public void testUpdate() throws Exception { String sql = " UPDATE DOG SET health = 90 WHERE id = 4 "; try { this.insertOrUpdateOrDelete(sql ); } catch (Exception e) { e.printStackTrace(); } } // 3. 删除 @Test public void testDelete() { String sql = " DELETE FROM DOG WHERE ID = 4 "; try { this.insertOrUpdateOrDelete(sql ); } catch (Exception e) { e.printStackTrace(); } } // 4. 查询 @Test public void testSelectDog() throws Exception { String sql = " SELECT * FROM DOG "; ResultSet rs = stmt.executeQuery(sql); List<Dog> list = new ArrayList<Dog>(); while(rs.next()) { Dog dog = new Dog(); dog.setId(rs.getInt("id")); dog.setName(rs.getString("name")); list.add(dog); }
3、防止注入
@Test public void testPpStmt() { Connection conn= null; PreparedStatement pstm = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xdsc", "root", "root"); String sql = " SELECT * FROM MASTER WHERE NAME=? AND PASSWORD=? "; pstm = conn.prepareStatement(sql); // 将占位符赋值 // SELECT * FROM MASTER WHERE NAME=‘123123‘ AND PASSWORD=‘YEAHSIR‘ pstm.setString(1, "YEAHSIR"); pstm.setString(2, "123123"); // 执行SQL rs = pstm.executeQuery(); while(rs.next()) { Master master = new Master(rs.getInt("id"), rs.getString("name"), rs.getString("password"), rs.getInt("money")); System.out.println(master); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); System.out.println("关闭结果集出了问题"); } try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }