简体   繁体   English

JDBC。 sql中的prepareStatement增量值

[英]jdbc. preparedStatement incrementing value in sql

I have 2 tables in database authors (author_id, first_name, last_name); books (book_id, book_title, book_author_id); 我在数据库authors (author_id, first_name, last_name); books (book_id, book_title, book_author_id);有2个表authors (author_id, first_name, last_name); books (book_id, book_title, book_author_id); authors (author_id, first_name, last_name); books (book_id, book_title, book_author_id); book_author_id is fk to author_id book_author_id与author_id对应

and when im trying to fill database for tests 当我试图填充数据库进行测试时

    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);
    }

receiving this log 收到此日志

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)

as you can see preparedStatement increment book_author_id by 1 each time when im saving book into database, but it shouldn't do this. 正如您看到的那样,当我将书籍保存到数据库中时,每次都会将prepareStatement的book_author_id递增1,但这不应该这样做。 can you please explain why this happening and how to fix this. 您能否解释一下为什么会发生这种情况以及如何解决此问题。 if i will use just database console sql queries it will work, but if using prepared statement got this problem. 如果我仅使用数据库控制台sql查询,它将起作用,但是如果使用prepared语句,则会出现此问题。 Added book dao save method 增加了书道保存方法

 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 same method with select * from books where book_title = 'title' and book_author_id = id return true if exists and false if doesnt isExists与select * from书籍的方法相同,其中book_title ='title'和book_author_id = id的书籍如果存在则返回true,否则返回false

when you look at your code sample: you're setting the second parameter of your prepared statement to the book id, instead of the book_author_id. 当您查看代码示例时:您将准备好的语句的第二个参数设置为book id,而不是book_author_id。

Your code: 您的代码:

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

but it should be 但这应该是

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

as a matter of fact- the ID of the books is incrementing by one for each 实际上-图书的ID每增加一

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JDBC。 替换列的所有行值 - JDBC. Replace in all rows value of the column SQL - PreparedStatement - 效率 - JDBC - SQL - PreparedStatement - Efficiency - JDBC JDBC在PreparedStatement中生成SQL - JDBC generation of SQL in PreparedStatement 无法通过JDBC连接到SQL Server。 找不到适用于jdbc:sqlserver://的驱动程序 - Unable to connect to SQL Server via JDBC. No suitable driver found for jdbc:sqlserver:// 如何在带有PreparedStatement的JDBC中使用批处理SQL? - How to use batch SQL in JDBC with PreparedStatement? JDBC:使用PreparedStatement创建表,SQL语法错误与否? - JDBC: Create Table with PreparedStatement, SQL Syntax Error or not? PreparedStatement的使用; 可能容易受到 SQL 注入(使用 JDBC) - This use of PreparedStatement; can be vulnerable to SQL injection (with JDBC) JDBC中的PreparedStatement - PreparedStatement in JDBC 带有PreparedStatement.setTimestamp的Java JDBC SQL语法错误。 时间在冒号':'处被截断 - Java JDBC SQL Syntax error with PreparedStatement.setTimestamp. Value gets cut off at the colon ':' in time org.sqlite.jdbc4.JDBC4PreparedStatement.setBinaryStream(JDBC4PreparedStatement.java:96)上的java.sql.SQLFeatureNotSupportedException - java.sql.SQLFeatureNotSupportedException at org.sqlite.jdbc4.JDBC4PreparedStatement.setBinaryStream(JDBC4PreparedStatement.java:96)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM