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

Nar*_*des 1 java mysql sql database prepared-statement

我在 Mysql 中创建了一个表,使用

Create table 
(
 id int auto_increment,
 us varchar(100),
 ps varchar(1000)
); 
Run Code Online (Sandbox Code Playgroud)

并使用 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);}  
              
    }
Run Code Online (Sandbox Code Playgroud)

一切正常

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

我不能像这样添加,而通过java添加就像只添加我们一样,ps列和id将自动递增。

有没有什么方法可以在不传递参数的情况下添加数据?

for*_*pas 5

id从sql语句中删除该列:

String query = "insert into login (us, ps) values (?, ?)";
Run Code Online (Sandbox Code Playgroud)

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

preparedStmt.setInt(1, id++); 
Run Code Online (Sandbox Code Playgroud)

id该列auto_inrement的值将由 MySql 设置。
当然,将其他行的索引更改为 1 和 2:

preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
Run Code Online (Sandbox Code Playgroud)