James Montgomery Boice reflects on Psalm 40, discussing the reasons for David's words in verse 2, that he was dragged up from the "miry bog," as the ESV puts it (NIV: slimy pit):
Some people have a very different kind of pit from which they need to be lifted. It is the pit of personal defeat, whether at work or school or in the home or in some other setting or relationship. Some people would say that their entire lives have been one long and unending defeat. They have never succeeded at anything.
I do not know the answer in your specific case, of course. And I do not want to trivialize your discouragement or make light of it. But I can tell you this. God does have things he wants you to succeed at, and he will enable you to succeed at those, even though they may be different from what you are doing now. The place to begin is where David began. He began by laying his problems before the Lord. I repeat that I do not know what David was referring to by his metaphor of the pit, but there was a time early in his life when he could have spoken very graphically about his defeats. No matter what he did he was unable to please King Saul, and Saul in his hatred and jealousy of David ruthlessleslly hounded the young man from place to place. It was many years before the Lord intervened to remove Saul and eventually bring David to the throne. If you are defeated, bring your defeats to God. Wait on God. David "waited patiently for the Lord." That is how Psalm 40 begins (v.1). If you wait patiently, you too will learn that God has more important things for you to do, and he will give you significant victories in his own pefect time.