Java实现对mysql数据库的增删查改

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zyq_hh/article/details/51673435

前面我们已经讲过如何实现对mysql数据库的连接。最简单的数据库操作就是增删查改。

其实对懂得实现对数据库的连接,其余的,对于一些简单的操作都是很简单的。

查看数据

public static void show_info() throws ClassNotFoundException, SQLException{
    	sql = "select * from stu_info";
    	Connection con = connect();
    	Statement st = con.createStatement();
    	ResultSet rs = st.executeQuery(sql);
    	System.out.println("学号\t姓名\t出生日期         \t性别\t课程号");
        while(rs.next()){
        	System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4)+"\t"+rs.getString(5));
        }
        con.close();
    }


添加数据


 public static void insert() throws ClassNotFoundException, SQLException{
    	Connection con = connect();
    	System.out.println("请输入数据:");
    	Scanner input = new Scanner(System.in);
    	int sID = input.nextInt();
    	String sName = input.next();
    	String brithday = input.next();
    	String sex = input.next();
    	String s_cid = input.next();
    	Statement st = con.createStatement();
    	sql = "insert into stu_info values(?,?,?,?,?)";
        PreparedStatement pre = (PreparedStatement) con.prepareStatement(sql);
        pre.setInt(1, sID);
        pre.setString(2, sName);
        pre.setString(3, brithday);        
        pre.setString(4, sex);
        pre.setString(5, s_cid);
        int count = pre.executeUpdate();
        System.out.println(count+"条数据发生了变化");
        pre.close();
        con.close();
    }


修改数据

    public static void modify() throws ClassNotFoundException, SQLException{
    	Connection con = connect();
    	Scanner input = new Scanner(System.in);
    	System.out.println("输入修改的学号");
    	int sID = input.nextInt();
    	
    	System.out.println("输入修改信息");
    	String sName = input.next();
    	String brithday = input.next();
    	String sex = input.next();
    	String s_cid = input.next();
        sql  ="update stu_info set sName = ?,birthday = ?,sex = ? ,s_cid = ? where sID = " +sID;
        PreparedStatement pre = (PreparedStatement) con.prepareStatement(sql);
        pre.setString(1, sName);
        pre.setString(2, brithday);
        pre.setString(3, sex);
        pre.setString(4, s_cid);
        int count = pre.executeUpdate();
        System.out.println(count+"条数据发生变化");
        pre.close();
        con.close();
    }

删除数据

  public static void delete() throws ClassNotFoundException, SQLException{
        Connection con = connect();
        System.out.println("输入删除的学号");
    	Scanner input = new Scanner(System.in);
        int sID = input.nextInt();
        sql = "delete from stu_info where sID = " +sID;
        Statement st = con.createStatement();
        int count = st.executeUpdate(sql);
        System.out.println(count+"条数据发生了变化");
        con.close();
    }

这里出现了两个不同的类Statement 和PrepardStatement。其中 PrepardStatement是由Statement继承过来的。

PrepardStatement提高了代码的可读性和维护性

猜你喜欢

转载自blog.csdn.net/zyq_hh/article/details/51673435