Yes, the Spirit was always with David.
- David was given the Holy Spirit before he committed adultery.
- David prayed to not have the Holy Spirit taken from him after he committed adultery.
- David was forgiven by God for adultery and spared the consequence under the law.
- David never turned aside from anything God commanded him after he repented.
In light of those facts, it's reasonable to say the Holy Spirit didn't prevent David from committing adultery; but how do you explain him keep the law after that?
Was the cause of his reform the Holy Spirit that was renewed in him, or his own efforts to keep the Mosaic laws, or both?
1 Samuel 16 KJV
(13) Then Samuel took the horn of oil, and anointed him in the midst of his brethren: and the Spirit of the LORD came upon David from that day forward. So Samuel rose up, and went to Ramah.
(13) Then Samuel took the horn of oil, and anointed him in the midst of his brethren: and the Spirit of the LORD came upon David from that day forward. So Samuel rose up, and went to Ramah.
And yes, he committed murder and adultery while he had the Spirit.
As to what caused him to keep the law, I'm sure it was a combination of things, the Spirit included.
He also had the law; a check list for him to follow.
Don't commit adultery (any more), CHECK.
Don't murder (any more), CHECK.
But we also know that keeping the law is not what saves a person.
The rich young ruler was also said to have kept the law, but it didn't guarantee him eternal life.
So even if it was only the Spirit that made him keep the law, it did not save him.
Because the law is not of faith, and that by the works of the law will no flesh be justified.
The just shall live by faith.