What afflictions did Hashem put on him?
Rashi: Galus.
Rashi (27): If this refers to David, for the episode of Bas Sheva "Tachas ha'Kivsah Yeshalem Arbatayim 1 ", and he became a Metzora for six months.
Radak: It is his evil days (when David was pursued).
Yuma 22b: David was afflicted via four of his children - the first baby of Bas Sheva, Amnon, Tamar and Avshalom. Yalkut Shimoni (Shmuel I, 121) lists Adoniyahu in place of Tamar.
Why does it say "He did not give me to death"?
Rashi: Galus atoned for his sins, therefore he will live.
"Gam Hashem He'evir Chatascha Lo Samus" (Shmuel II, 12:13).
Radak: My afflictions were to cleanse me of my sin. He did not want to kill me!
Sha'arei Teshuvah (4:13, citing Shocher Tov 38:1): One who does not know how to hit, he hits his son on his eyes or face. 1 One who knows how to hit, he hits his son in a way that will not damage.
Malbim: (a) The afflictions were in place of death; the atoned for his sins. (b) His Nefesh will not die, since He will tell Hashem's deeds, and he received Kaparah via afflictions.
Our version of the Midrash expounds this on "Al b'Kitzpecha Sochicheni uva'Chamasecha Syeasreni" (38:2), "Yasreni Hashem Ach b'Mishpat" (Yirmeyah 10:24). (PF)