原⽣jdbc与预处理对象PreparedStatment 3

原生JDBC增删改查操作

插入

@Test
public void testJDBC2() throws SQLException, ClassNotFoundException {
    /**
    * JDBC 完成记录的插⼊
    * 1.注册驱动
    * 2.获得连接
    * 3.获得执⾏sql语句的对象
    * 4.执⾏sql语句, 并返回结果
    * 5.处理结果
    * 6.释放资源
    */
    //1,注册驱动
    Class.forName("com.mysql.jdbc.Driver");
    //2,获取连接
    String url = "jdbc:mysql://localhost:3306/mydb";
    Connection conn = DriverManager.getConnection(url, "root","root");
    //3,获取执行sql语句的对象
    Statement stat = conn.createStatement();
    //4,准备sql语句
    String sql = "insert into category(cname) values('测试')";
    //5,用连接对象执行SQL语句,并返回结果集
    int result = stat.executeUpdate(sql);
    //6,处理结果
    System.out.println("result = " + result);
    //7,关闭资源
    stat.close();
    conn.close();
}

修改

@Test
public void testJDBC3() throws SQLException, ClassNotFoundException {
    /**
    * JDBC 完成记录的更新
    * 1.注册驱动
    * 2.获得连接
    * 3.获得执⾏sql语句的对象
    * 4.执⾏sql语句, 并返回结果
    * 5.处理结果
    * 6.释放资源
    */
    Class.forName("com.mysql.jdbc.Driver");

    String url = "jdbc:mysql://localhost:3306/mydb";
    Connection conn = DriverManager.getConnection(url, "root","root");

    Statement stat = conn.createStatement();

    String sql = "update category set cname='测试2' where cid=4";

    int result = stat.executeUpdate(sql);

    System.out.println("result = " + result);

    stat.close();
    conn.close();
}

删除

@Test
public void testJDBC4() throws SQLException, ClassNotFoundException {
    /**
    * JDBC 完成记录的删除
    * 1.注册驱动
    * 2.获得连接
    * 3.获得执⾏sql语句的对象
    * 4.执⾏sql语句, 并返回结果
    * 5.处理结果
    * 6.释放资源
    */
    Class.forName("com.mysql.jdbc.Driver");
    
    String url = "jdbc:mysql://localhost:3306/mydb";
    Connection conn = DriverManager.getConnection(url, "root","root");
    
    Statement stat = conn.createStatement();
    
    String sql = "delete from category where cid=4";
    
    int result = stat.executeUpdate(sql);
    
    System.out.println("result = " + result);
    
    stat.close();
    conn.close();
}

查询

@Test
public void testJDBC5() throws SQLException, ClassNotFoundException {
    /**
    * JDBC 完成记录的查询
    * 1.注册驱动
    * 2.获得连接
    * 3.获得执⾏sql语句的对象
    * 4.执⾏sql语句, 并返回结果
    * 5.处理结果
    * 6.释放资源
    */
    // 通过id 查询数据
    Class.forName("com.mysql.jdbc.Driver");

    String url = "jdbc:mysql://localhost:3306/mydb";
    Connection conn = DriverManager.getConnection(url, "root","root");

    Statement stat = conn.createStatement();

    String sql = "select * from category where cid = 3";

    ResultSet rs = stat.executeQuery(sql);
    
    if (rs.next()) {
        int cid = rs.getInt("cid");
        String cname = rs.getString("cname");
        System.out.println("cid = " + cid + ",cname = " +cname);
    } else {
        System.out.println("数据没有查到");
    }
    
    rs.close();
    stat.close();
    conn.close();
}

猜你喜欢

转载自blog.csdn.net/weixin_40959890/article/details/107746436