向MYSQL數據庫的表中插入有自動加一主鍵的數值

昨天晚上沒搞成,早上起來搞定了!

原來的表中ACCOUNT中 ID  不是自動增加的,別人註冊賬戶的時候需要制定ID,這個是很不好的,所以把ID

設定爲自動加一,用戶不用管ID,只註冊登記其他的信息,所以修改MYSQL。

mysql> ALTER TABLE `database`.`table` MODIFY COLUMN `id` INTEGER AUTO_INCREMENT;


然後實現程序中的增加,問題出現了,我在MYSQL中可以用這樣的語句:


mysql>insert into accounts values( ' ' ,'username','password');

但是在程序中卻不行!比如:

strSql="insert into account values(' ','"+username+"','"+password+"')";
       
       
      
        try {
            connect =dataSource.getConnection();
            Statement stmt=connect.createStatement();
            result =stmt.executeUpdate(strSql);
        } catch (SQLException ex) {
            System.err.println(ex.getMessage());// TODO: handle exception
        }

於是想,乾脆先求ID的最大值,然後插入時加一,寫個函數:

public int MAX_ID()throws Exception{
        Connection connect =null;
        String strSql;
        ResultSet rs;
        int maxId=0;
        strSql="select MAX(id) FROM account";
        try {
           
             connect=dataSource.getConnection();
             Statement stmt=connect.createStatement();
             rs=stmt.executeQuery(strSql);
             if(rs.next())
             maxId=Integer.parseInt(rs.getString(1));
    // maxId=Integer.parseInt(rs.getString("id ")); 這樣寫不行,報錯說ID列有錯之類的,找不到原因!
             
           
        } catch (SQLException e) {
            e.printStackTrace();
        }
       
        finally{
            if(connect!=null)connect.close();
        }
        return maxId;
       
    }

然後在插入函數時:這樣寫:


public int Insert(String username,String password)throws Exception{
       
       Connection connect=null;
        String strSql;
       
        int result =0,maxID;
      
     maxID=this.MAX_ID()+1;//剛纔求出的最大數值!
       
    strSql="insert into account values('"+maxID+"','"+username+"','"+password+"')";
       
       
//strSql="insert into account values(maxID,'"+username+"','"+password+"')";這樣寫也報錯!

        try {
            connect =dataSource.getConnection();
            Statement stmt=connect.createStatement();
            result =stmt.executeUpdate(strSql);
        } catch (SQLException ex) {
            System.err.println(ex.getMessage());// TODO: handle exception
        }
   
    finally{
        if(connect!=null)connect.close();
    }
   
    return result;
    }
   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章