1. 程式人生 > >Java實現對mysql資料庫的增刪查改

Java實現對mysql資料庫的增刪查改

前面我們已經講過如何實現對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提高了程式碼的可讀性和維護性