David's song in 2 Samuel 22 is almost identical to Psalm 18 which contains the following prelude:
For the director of music. Of David the servant of the Lord. He sang to the Lord the words of this song when the Lord delivered him from the hand of all his enemies and from the hand of Saul.
David wrote this song before the affair of Bathsheba. So the placement of this song in 2 Samuel 22 was not chronologically accurate.
He opened the song with
2 “The Lord is my rock, my fortress and my deliverer;
3 my God is my rock, in whom I take refuge,
my shield and the horn of my salvation.
He is my stronghold, my refuge and my savior
The following need to be interpreted under the above heading and context:
For all His ordinances were before me, and as for His statutes, I did not depart from them. I was also blameless toward Him, and I kept myself from my iniquity.
Why would David state that he was blameless towards the Lord?
David took refuge in God. That's how he could become blameless. He was shielded by God.
What does the interesting phrase, “I kept myself from my iniquity” mean?
He wrote this before the encounter with Bethsheba. He refused to kill Saul in e.g., 1 Samuel 24:6
He said to his men, "The LORD forbid that I should do such a thing to my master, the LORD's anointed, or lay my hand on him; for he is the anointed of the LORD."
Another example was Joab killed Abner in cold blood.
2 Samuel 3:37
So on that day all the people there and all Israel knew that the king [David] had no part in the murder of Abner son of Ner.
Another example had to do with Nabal and his men.
1 Samuel 25:32 David said to Abigail, “Praise be to the Lord, the God of Israel, who has sent you today to meet me. 33May you be blessed for your good judgment and for keeping me from bloodshed this day and from avenging myself with my own hands.
David did try to keep himself from iniquity. He was a conscientious person before God, a man after God's heart.