in reply to Avoiding too many DB queries

The big optimization I see if to not make a new connection to the database for each call. I am assuming you are calling this method many times in a loop. Make the connection once, process the loop, and then disconnect.

Another optimization is to cache the results if you do the same lookups repeatedly. For example, keep a hash that maps atom name to aid. If the mapping is not found, call the database, else use the value.

Which database are you using? With some databases, it can't make sense to rely on the database to check the keys and report an error when a row already exists. Your code rolls back the whole transaction and goes on the next item.