This Psalm was composed either when David was in great distress, or afterwards, in remembrance thereof, and of God’s singular goodness in delivering him out of it, whence it is mixed of prayer and praises, of hopes and fears. But what those particular troubles were which David here speaks, is only matter of conjecture, and therefore I shall rather omit than confidently determine.
David prayeth for preservation, according to his confidence which he putteth in God, Psa_31:1-6, that he might rejoice in his mercy, Psa_31:7,8. He declareth what he suffered from his enemies and friends, Psa_31:9-13; but magnifieth the care and tenderness of God, Psa_31:14-18; and praiseth him for his goodness to himself and to the faithful, Psa_31:19-24.
Let me never be ashamed, to wit, of my confidence in thy promises.
In thy righteousness, i.e. by or for; or, according to thy faithfulness and goodness; both which come oft under the name of righteousness.