向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;
    }
   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章