Post by zggamePost by Gordon Burditt1. =A0insert into Product (...)
Presumably, Product.ID here is an auto_increment field, otherwise
you'd know what the value here is without having to select it.
Yes. That is what we did.
Post by Gordon Burditt3. =A0insert into Format (ProductID,....) value (x, ...)
2. =A0insert into Format (ProductID, .....) values (last_insert_id(), ...=
)
Post by Gordon BurdittNote: =A0last_insert_id() works on a *PER-CONNECTION* basis, so other
instances of this code also inserting new records won't affect
last_insert_id(). =A0That situation will, however, screw up max(ID)
if the timing happens to turn out wrong.
Is this last_insert_id() a build-in function of mysql?
Yes.
Post by zggameI am using
java (jdbc). What do you mean "per-connection basis"? Does that mean
that I need to use Statement generated by the same Connection
object?
I don't really understand how you use MySQL from Java, but you've
probably got the right idea here. You connect (on a network level,
by TCP connection) to MySQL, giving login and database info. Then
you do a series of queries and get results. Sometimes previous
queries affect later ones (such as SET queries, or side effects on
last_insert_id() or user variables). Then you close the connection.
The connection would probably be represented as an object in Java.
"Per-connection" means that changes made to one connection do not
affect other connections. Examples of such things include the
current database, the value of last_insert_id(), the value of local
user variables, the character set of the connection, etc.
Post by zggamePost by Gordon BurdittIf you are using InnoDB tables, you can combine these two queries
into one transaction.
We do use InnoDB engine and we enforced the foreign key. Could you
please explain this a bit more? Thank you very much.
If you don't know what a transaction is, I'm not going to try and
teach you how to use them (books on the subject can get pretty
difficult for one person to lift). A transaction is a sequence of
queries that appear to the outside (other users/connections) to
either all happen at once or none happen. MySQL transactions work
on InnoDB tables but not MyISAM tables. Transactions are less
restrictive than locking all the tables. Example:
SET AUTOCOMMIT = 0;
START TRANSACTION;
INSERT INTO Product values (.....);
INSERT INTO Format values (......);
COMMIT;
Other connections will not see the intermediate state where you
have a Product record and no Format record. If something botches
one query, such as the INSERT into the Format table, previous queries
such as the insert into the Product table will be rolled back.