🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
```java public class StudentTest { /** * 查询 */ @Test public void select() throws SQLException { //1. 连接数据库 Connection conn = ConnUtils.getConnection3(); //2. 编写select语句 String sql = "select id,name,age,sex from student"; //3. 调用prepareStatement方法返回一个预执行对象 PreparedStatement pstmt = conn.prepareStatement(sql); //4. 执行SQL语句并返回结果 ResultSet rs = pstmt.executeQuery(); //5. 处理结果 while (rs.next()) { System.out.println(rs.getString("id") + ", " + rs.getString("name") + ", " + rs.getString("age") + ", " + rs.getString("sex")); } //1001, 张三, 25, 男 //1002, 小美, 25, 女 //6. 关闭资源(遵循后开先关) rs.close(); pstmt.close(); conn.close(); } /** * 预处理。 * 进行预处理需要用到 ? 通配符与 setXXX 类方法结合使用。 */ @Test public void prepared() throws SQLException { //1. 连接数据库 Connection conn = ConnUtils.getConnection3(); //2. 编写SQL语句 String sql = "select id,`name`,age,sex from student where id=?"; //3. 调用prepareStatement方法返回一个预执行对象 PreparedStatement pstmt = conn.prepareStatement(sql); //setString(int parameterIndex, String x) //parameterIndex为 从左往右数第几个通配符 ?,从1开始 pstmt.setString(1, "1002"); //4. 执行SQL语句 ResultSet rs = pstmt.executeQuery(); //5. 处理结果 while (rs.next()) { System.out.println(rs.getString("id") + ", " + rs.getString("name") + ", " + rs.getString("age") + ", " + rs.getString("sex")); } //1002, 小美, 25, 女 // 6. 关闭资源(遵循后开先关) rs.close(); pstmt.close(); conn.close(); } /** * 插入 */ @Test public void insert() throws SQLException { //1. 连接数据库 Connection conn = ConnUtils.getConnection3(); //2. 编写insert语句 PreparedStatement pstmt = conn.prepareStatement("insert into student values(?,?,?,?)"); pstmt.setString(1, "1003"); pstmt.setString(2, "李四"); pstmt.setInt(3, 27); pstmt.setString(4, "男"); //3. 执行SQL,返回的是数据库中受到影响的行数 int result = pstmt.executeUpdate(); //4. 关闭资源 pstmt.close(); conn.close(); } /** * 更新 */ @Test public void update() throws SQLException { //1. 连接数据库 Connection conn = ConnUtils.getConnection3(); //2. 编写update语句 PreparedStatement pstmt = conn.prepareStatement("update student set `name` = ? where sex = ? "); pstmt.setString(1, "王五"); pstmt.setString(2, "男"); //3. 执行SQL,返回的是数据库中受到影响的行数 int result = pstmt.executeUpdate(); //4. 关闭资源 pstmt.close(); conn.close(); } /** * 删除 */ @Test public void delete() throws SQLException { //1. 连接数据库 Connection conn = ConnUtils.getConnection3(); //2. 编写delete语句 PreparedStatement pstmt = conn.prepareStatement("delete from student where id = ?"); pstmt.setString(1, "1002"); //3. 执行SQL,返回的是数据库中受到影响的行数 int result = pstmt.executeUpdate(); //4. 关闭资源 pstmt.close(); conn.close(); } } ```