今日学习的 jdbc statement的增删改

2024-01-07 18:54:28

首先要获取jdbc文件

         Class.forName("com.mysql.jdbc.Driver");

连接数据库(数据库要提前打完在写增删改查)

         Connection  connection=
DriverManager.getConnection("jdbc:mysql://localhost:3306/db_day11","root","root");

后面两个字段是账户和密码下载数据库设置的密码

Statement就是用来向数据库发送要执行的SQL语句的对象。

	Statement stmt = con.createStatement();

添加

  @Test
    public void insert() throws Exception {
        //1.获取连接对象,与数据库建立连接
        Connection con = getConnection();
        //2.获取sql执行对象
        Statement stmt = con.createStatement();
        //3.编写sql
        String sql = "insert into user values(null,'zhaoliu', '789')";
        //4.执行sql
        int i = stmt.executeUpdate(sql);
        System.out.println("插入成功,影响的行数:"+i);
        //5.释放资源
        stmt.close();
        con.close();
    }

修改数据

   public static void main(String[] args) throws Exception {
      Class.forName("com.mysql.jdbc.Driver");
        Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/db_day11","root","root");
       Statement statement=connection.createStatement();
        int i1=statement.executeUpdate("update student set name='小伙'where id=3");
        System.out.println(i1);
       statement.close();
        connection.close();
    }

删除数据

 public static void fun2(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/db_day11","root","root");
        Statement statement=connection.createStatement();
        ResultSet resultSet = statement.executeQuery(" delete from student where name='小伙'");

        statement.close();
        connection.close();
    }

重要的东西说三遍!

关闭数据要采用后行先关!!

关闭数据要采用后行先关!!

关闭数据要采用后行先关!!

文章来源:https://blog.csdn.net/sxs04/article/details/135403604
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。