How can I get the Id of a record which has been inserted using Apex?
The platform allocates an ID value and sets it in an SObject's ID field implicitly as part of the insert operation:
Account a = new Account(Name = 'Acme'); // a.Id is null here insert a; // a.Id now has a value set by the platform
So most of the time you do not assign a value to an object's ID field. An exception is where you have the ID of the object (perhaps from a lookup field on a different object) and want to update the object. In that case you can assign the ID and so save having to first query the object:
Account a = new Account(Id = accountId, Name = 'New Name'); update a;
If you are using statement like "insert account;", the Id of the account can be accessed by "account.Id;". Below code will give you an overview.
Account acct = new Account(Name='SFDC Account'); insert acct; system.debug("Inserted Account Id = "+acct.Id);
acct.Id will provide the Id for the Account record acct.The debug statement above will write the Id to the Debug logs.
Please visit the below link for DML usage and using Id for subsequent logic(s) : http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_dml_examples_insert_update.htm