java - trigger to update two tables at the same time
高洛峰
高洛峰 2017-06-28 09:23:33
0
2
906

Using mysql, book management, the problem involves two tables, books and lender

Here comes the question:

Create a trigger to realize the automatic increment of the borrowed books/decrease of the returned books, but the trigger I wrote cannot realize this function, and the final amount has not changed (some amounts in the table were entered manually by me) )

When books are borrowed and the islend attribute is updated, the amount of borrowed books is updated in the lender table at the same time.
After the islend attribute is updated, what is saved is the id of the borrower, the lender. The id in the lender is the primary key, and the islend in the books table is Foreign key, connects these two tables.

The two database table structures are given below. The triggers currently written are as follows:

CREATE TRIGGER returnBook
AFTER UPDATE ON books
FOR EACH ROW
BEGIN
UPDATE lender
SET amount = lender.amount - 1
WHERE id = new.isLend;
END

The render table structure is as follows:

The books table structure is as follows:

Test statement
String sql = "UPDATE books SET isLend=?,date=NULL WHERE bookId=? AND isLend=?";

    try {
        ps = conn.prepareStatement(sql);
        ps.setString(1, "1");
        ps.setString(2, String.valueOf(bookId));
        ps.setString(3, String.valueOf(id));
        row = ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }

The borrowing/returning function can be implemented normally, but the trigger function is not implemented

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
学霸
CREATE TRIGGER lendBook
AFTER UPDATE ON books
FOR EACH ROW
BEGIN
sql语句1;
sql语句2;
END
我想大声告诉你

There is nothing wrong with the trigger itself, except that we need to pay attention to the null problem mentioned by @夜 vanishing in the summer [lingchenxiaoshixiari]

You can add a log-like table to the trigger to see if the trigger has been executed

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template