【问题标题】:jdbc. preparedStatement incrementing value in sql数据库。 sql中的preparedStatement递增值
【发布时间】:2019-05-29 21:10:49
【问题描述】:

我在数据库中有 2 个表 authors (author_id, first_name, last_name); books (book_id, book_title, book_author_id); book_author_id 是 author_id 的 fk

当我试图填充数据库进行测试时

    private static BookDao dao = new BookDaoImpl(new DBConnection("liquibase/liquibase.properties"));
    private static Author author1 = new Author(1, "Joshua", "Bloch");
    private static Author author2 = new Author(2, "Robert", "Martin");
    private static Book book1 = new Book(1, "Effective Java", 1);
    private static Book book2 = new Book(2, "Java Puzzlers: Traps, Pitfalls, and Corner Cases", 1);
    private static Book book3 = new Book(3, "Clean code", 2);
    private static Book book4 = new Book(4, "Clean Architecture", 2);

    @BeforeClass
    public static void fillDataBases() throws DAOException {
        authorDao.save(author1);
        authorDao.save(author2);
        dao.save(book1);
        dao.save(book2);
        dao.save(book3);
        dao.save(book4);
    }

收到此日志

2019-05-29 23:48:26 - starting to check if author exists in database
2019-05-29 23:48:26 - creating statement for finding author by name
2019-05-29 23:48:26 - sql : 'SELECT * from authors WHERE first_name = ? AND last_name = ?', parameters : ['Joshua','Bloch']
2019-05-29 23:48:26 - author doesn't exist in database. you can save new author
2019-05-29 23:48:26 - creating statement for saving new author
2019-05-29 23:48:26 - sql : 'insert into authors(first_name, last_name) values(?,?)', parameters : ['Joshua','Bloch']
2019-05-29 23:48:26 - new author saved
2019-05-29 23:48:26 - starting to check if author exists in database
2019-05-29 23:48:26 - creating statement for finding author by name
2019-05-29 23:48:26 - sql : 'SELECT * from authors WHERE first_name = ? AND last_name = ?', parameters : ['Robert','Martin']
2019-05-29 23:48:26 - author doesn't exist in database. you can save new author
2019-05-29 23:48:26 - creating statement for saving new author
2019-05-29 23:48:26 - sql : 'insert into authors(first_name, last_name) values(?,?)', parameters : ['Robert','Martin']
2019-05-29 23:48:26 - new author saved
2019-05-29 23:48:26 - creating statement for finding book by title and author
2019-05-29 23:48:26 - sql : 'SELECT * from books WHERE book_title = ? AND book_author_id = ?', parameters : ['Effective Java',1]
2019-05-29 23:48:26 - book doesn't exist in database. we can save new book
2019-05-29 23:48:26 - creating statement for saving new book
2019-05-29 23:48:26 - book title Effective Java book author's id 1
2019-05-29 23:48:26 - sql : 'insert into books(book_title, book_author_id) values(?,?)', parameters : ['Effective Java',1]
2019-05-29 23:48:26 - new book saved
2019-05-29 23:48:26 - creating statement for finding book by title and author
2019-05-29 23:48:26 - sql : 'SELECT * from books WHERE book_title = ? AND book_author_id = ?', parameters : ['Java Puzzlers: Traps, Pitfalls, and Corner Cases',1]
2019-05-29 23:48:26 - book doesn't exist in database. we can save new book
2019-05-29 23:48:26 - creating statement for saving new book
2019-05-29 23:48:26 - book title Java Puzzlers: Traps, Pitfalls, and Corner Cases book author's id 1
2019-05-29 23:48:26 - sql : 'insert into books(book_title, book_author_id) values(?,?)', parameters : ['Java Puzzlers: Traps, Pitfalls, and Corner Cases',2]
2019-05-29 23:48:26 - new book saved
2019-05-29 23:48:26 - creating statement for finding book by title and author
2019-05-29 23:48:26 - sql : 'SELECT * from books WHERE book_title = ? AND book_author_id = ?', parameters : ['Clean code',2]
2019-05-29 23:48:26 - book doesn't exist in database. we can save new book
2019-05-29 23:48:26 - creating statement for saving new book
2019-05-29 23:48:26 - book title Clean code book author's id 2
2019-05-29 23:48:26 - sql : 'insert into books(book_title, book_author_id) values(?,?)', parameters : ['Clean code',3]
2019-05-29 23:48:26 - (conn=1118) Cannot add or update a child row: a foreign key constraint fails (`myapp`.`books`, CONSTRAINT `fk_author_books` FOREIGN KEY (`book_author_id`) REFERENCES `authors` (`author_id`) ON DELETE CASCADE ON UPDATE CASCADE)

当我将书籍保存到数据库时,您可以看到preparedStatement 每次将 book_author_id 增加 1,但它不应该这样做。你能解释一下为什么会发生这种情况以及如何解决这个问题。如果我只使用数据库控制台 sql 查询它会工作,但如果使用准备好的语句会出现这个问题。 添加 book dao 保存方法

 public int save(Book book) throws DAOException {
        int i = 0;
        if (!isExists(book.getTitle(), book.getAuthorId())) {
            String sql = "insert into books(book_title, book_author_id) values(?,?)";
            try (Connection connection = dbConnection.getConnection()) {
                logger.trace("creating statement for saving new book");

                try(PreparedStatement statement = connection.prepareStatement(sql)) {
                    statement.setString(1, book.getTitle());
                    statement.setLong(2, book.getId());
                    logger.trace("book title " + book.getTitle() + " book author's id " + book.getAuthorId());
                    logger.trace(statement);
                    i = statement.executeUpdate();
                    logger.trace("new book saved");
                    logger.trace(connection.getMetaData());
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                throw new DAOException("cannot save new book to database", e);
            }
        } else {
            throw new DAOException("book " + book.getTitle() + " by author "
                    + book.getAuthorId() + " already exists in database");
        }
        return i;
    }

isExists 与 select * from books where book_title = 'title' and book_author_id = id 的方法相同 如果存在则返回 true,如果不存在则返回 false

【问题讨论】:

    标签: java sql jdbc prepared-statement


    【解决方案1】:

    当您查看代码示例时:您将准备好的语句的第二个参数设置为书籍 ID,而不是 book_author_id。

    您的代码:

                    statement.setLong(2, book.getId());
    

    但应该是的

                    statement.setLong(2, book.getBookAuthorId()); // assuming the getter is called that way
    

    事实上,书籍的 ID 每增加一个

    【讨论】:

      猜你喜欢
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多