If you started with such tables.,.
create table books ( book_id integer primary key, book_title varchar(15) not null ); create table authors ( author_id integer primary key, author_name varchar(15) not null ); create table book_authors ( book_id integer not null references books (book_id), author_id integer not null references authors (author_id), primary key (book_id, author_id) );
., and if you need to insert a new book and a new author at the same time, you can execute an SQL transaction like this.
begin transaction; insert into books values (1, 'First book'); insert into authors values (1, 'First author'); insert into book_authors (book_id, author_id) values (1, 1); commit;
Using a single transaction ensures that either all three inserts are written to the database, or none of them. Alternatives
- to create an updatable view in the database, join all three tables and insert into the view
- to record the stored procedure in the database and insert through the stored procedure and
- to insert into each table separately, which suggests that having a book is important, even if you don’t know the author, and vice versa. (This is probably what I would do for books and authors.)
If you added a new book to an existing author, you would have performed a slightly different transaction.
begin transaction; insert into books values (2, 'Second book'); insert into book_authors (book_id, author_id) values (2, 1); commit;
I believe Delphi is like any other client language. Instead of literal integers, you should refer to some property of the data-driven controls, possibly the value or text property. And you completed the transaction in the click event.
If Delphi is sufficiently “data aware” —through controls bound to columns and rows in the database, such as its own access controls — you may not need to execute any SQL or do anything special to preserve any automatic identifier is the number generated by dbms; it will be available through one of the management properties. (Access forms and controls are knowledgeable about the data and how it works.) But if you need and you use the Microsoft OLEDB provider for access, you can use select @@identity
to get the last identifier number used in your connection.