微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用Java添加自动增量值?

如何解决如何使用Java添加自动增量值?

我在MysqL中使用创建了一个

Create table 
(
 id int auto_increment,us varchar(100),ps varchar(1000)
); 

并使用Java通过我的GUI应用程序添加值:

我使用以下方法将值添加数据库中:

public static void MysqL(String u,String p) throws NoSuchAlgorithmException,InvalidKeySpecException
    {
        String hashpass=passhash(p);//throws declaration for this statement
        try{  
            Class.forName("com.MysqL.cj.jdbc.Driver");  
            Connection con=DriverManager.getConnection("jdbc:MysqL://127.0.0.1:3306/bs","root","root");   
            String query = " insert into login (id,us,ps)"
                    + " values (?,?,?)";  
            Statement stmt=con.createStatement();  
            ResultSet rs=stmt.executeQuery("select * from login"); 
            int id=0;
            while(rs.next())
            {
                id= rs.getInt(1);
            }
            PreparedStatement preparedStmt = con.prepareStatement(query);
            preparedStmt.setInt(1,id++); //I don't want this method because id is auto increment
            preparedStmt.setString(2,u);
            preparedStmt.setString(3,hashpass);
            preparedStmt.execute();
            con.close();  
            }catch(Exception e){ System.out.println(e);}  
              
    }

一切正常

但是ID是auto_increment,在添加其他列值时我不需要在id中添加值。

我不能像通过添加我们那样通过Java添加那样的内容,ps列和id将自动增加

是否有任何方法可以在不传递参数的情况下添加数据?

解决方法

从sql语句中删除列id

String query = "insert into login (us,ps) values (?,?)";

并且不要在准备好的语句中为其设置任何值,因此删除此行:

preparedStmt.setInt(1,id++); 

idauto_inrement,因此其值将由MySql设置。
当然,将其他行的索引更改为1和2:

preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
,

您可能会插入不带ID的数据,因为它将通过SQL自动生成

public static void Mysql(String u,String p) throws NoSuchAlgorithmException,InvalidKeySpecException {
    String hashpass=passhash(p);
    try{  
        Class.forName("com.mysql.cj.jdbc.Driver");  
        Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");   
        String query = " insert into login (us,?)"; // CHECK HERE  
        Statement stmt=con.createStatement();  
        ResultSet rs=stmt.executeQuery("select * from login"); 
        PreparedStatement preparedStmt = con.prepareStatement(query);
        preparedStmt.setString(1,u);
        preparedStmt.setString(2,hashpass);
        preparedStmt.execute();
        con.close();  
    }catch(Exception e){
        System.out.println(e);}           
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。