今日学习的 jdbc statement的增删改

首先要获取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();
    }

重要的东西说三遍!

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

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

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

你可能感兴趣的:(学习)