简体   繁体   中英

jdbc insert datas into database with auto increment field

I have a problem with auto increment fields.

I created this table,

CREATE TABLE todo ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, title VARCHAR(255) NOT NULL, name VARCHAR(100) NOT NULL, sequence INT(1) NOT NULL, type VARCHAR(20) DEFAULT 'TODO', regdate DATETIME DEFAULT NOW(), PRIMARY KEY (id) );

I created this model object

public class TodoDto {
private Long id;
private String name;
private String regDate;
private int sequence;
private String title;
private String type;

public TodoDto(Long id, String name, String regDate, int sequence, String title, String type) {
    super();
    this.id = id;
    this.name = name;
    this.regDate = regDate;
    this.sequence = sequence;
    this.title = title;
    this.type = type;
}

public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getRegDate() {
    return regDate;
}
public void setRegDate(String regDate) {
    this.regDate = regDate;
}
public int getSequence() {
    return sequence;
}
public void setSequence(int sequence) {
    this.sequence = sequence;
}
public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getType() {
    return type;
}
public void setType(String type) {
    this.type = type;
}

@Override
public String toString() {
    return "TodoDto [id=" + id + ", name=" + name + ", regDate=" + regDate + ", sequence=" + sequence + ", title="
            + title + ", type=" + type + "]";
}

}

I created this to insert datas to the DB

public List<TodoDto> getTodos() {
    List<TodoDto> list = new ArrayList<>();

    try {
        Class.forName("com.mysql.jdbc.Driver");
    }catch (Exception e) {
        e.printStackTrace();
    }

    String sql = "SELECT * FROM todo";

    try(Connection conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);
            PreparedStatement ps = conn.prepareStatement(sql)){

        try(ResultSet rs = ps.executeQuery()){

            while(rs.next()) {
                Long id = rs.getLong("id");
                String title = rs.getString("title");
                String name = rs.getString("name");
                int sequence = rs.getInt("sequence");
                String regDate = rs.getString("regDate");
                String type = rs.getString("type");

                TodoDto todoDto = new TodoDto(id, title, name, sequence, regDate, type);
                list.add(todoDto);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }

    }catch(Exception e){
        e.printStackTrace();
    }

    return list;
}

I created this client to perform the TodoDao.java

    String title = "title";
    String name = "name";
    Long id = ???
    int sequence = 1;

    String type = "TODO";

    String currentDate = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);

    TodoDto todoDto = new TodoDto(id, name, currentDate, sequence, title, type);

    TodoDao todoDao = new TodoDao();
    int insertCount = todoDao.addTodo(todoDto);

    System.out.println(insertCount);

In this client, I don't know how should I initialize the Long id

The id on DB is gonna increase by itself.

So how should i initialize it?

I think it's a simple problem. But I don't have enough knowledge about it and no one to ask

Please let me know what should i do

Because database is in charge of incrementing, you don't have to initialize id in java.

You could remove NOT NULL. There is no need for it, auto increment will take care of it

id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT

And when you want to insert into db using java app use either syntax like this

INSERT INTO Persons (name,regDate,sequence,title,type)
VALUES ('','','','',''); 

// Notice i ignored field id

or

INSERT INTO Persons VALUES (NULL,'','','','','')

// Notice that i specified NULL in place where id value is expected

Edit: In case you have to specify id you can use command LAST_INSERT_ID() . Check this link for reference LAST_INSERT_ID() MySQL It will return the number of the next id that is going to be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM