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

來源:互聯網
上載者:User
昨天晚上沒搞成,早上起來搞定了!

原來的表中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;
    }
   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.