David wanted to be taken out of prison (Ps 142:6-142:7)

“Save me from my persecutors!

They are too strong for me.

Bring me out of prison!

So that I may give thanks to your name.

The righteous will surround me.

You will deal bountifully with me.”

This psalm ends with a plea from David to save him from his persecutors. They were too strong for him. He could not deal with them himself. He wanted to be brought out of prison. There is no specific time mentioned in the stories of David where he was actually in a prison. This might be a metaphor since he feels like he cannot move. If he escaped he would give thanks to the name of Yahweh. He wanted to be surrounded by the righteous ones. He felt that Yahweh would deal with him mercifully and bountifully.