The PM was asked about UK links with Saudi Arabia at an Ask The Leaders event hosted by Sky News and Facebook.
He defended close ties with the country despite its poor human rights record.
Mr Cameron said his first duty was to protect the public even if it meant doing business with regimes he "didn't always agree with".
During the event, Mr Cameron was asked why flags in the UK had been flown at half-mast on government buildings following the death of King Abdullah bin Abdulaziz of Saudi Arabia last month.
The case of blogger Raif Badawi, who has been sentenced in Saudi Arabia to 1,000 lashes for insulting Islam, was also raised.
Mr Cameron said: "I can tell you one time since I've been prime minister, a piece of information that we have been given by that country has saved potentially hundreds of lives here in Britain.
"Now, you can be prime minister and say exactly what you think about every regime in the world and make great headlines, and give great speeches.
"But I think my first job is to try and keep this country safe from terrorism and if that means you have to build strong relationships sometimes with regimes you don't always agree with, that I think is part of the job and that is the way I do it. And that is the best way I can explain it."
Mr Cameron was also asked whether the UK's relationship with the Arab kingdom was related to the fact that it has vast oil resources.
"Yes, of course," he said. "Of course Britain needs to have relationships with countries we trade with, including those that we buy oil and gas from.
"We can't make all our oil and gas here in the UK, we're doing well because we've got North Sea oil."
And Mr Cameron insisted he raised human rights issues with certain countries when he visited them.
He said: "It's perfectly possible to go to those countries as I do and raise human rights abuses.
"In fact I would argue that if you have a relationship with them and you have a way of talking to them they are more likely to listen to you than if you just cut yourself off."
A piece of counter-terrorism intelligence supplied by Saudi Arabia "saved potentially hundreds of lives" in the UK, David Cameron has revealed.