About 380 US Navy ships were sunk in combat during World War II. Only one of their captains, Charles B. McVey III of the USS Indianapolis, was court martialed for losing his ship and convicted - a very controversial action. McVey retained his rank of captain but lost his seniority, and was promoted to rear admiral when he retired in 1949. McVey was apparently the first captain of a US Navy ship to be courtmartialed for losing his ship in wartime.
So if the US Navy is a good example, Starfleet probably doesn't court martial captains for losing their ships in battle, considering enemy actions sufficient explanation, (they did court martial Picard for losing his ship in battle but that was a sneak attack by an unknown enemy during time of peace, so maybe that makes a difference). And if the US Navy is a good example, a captain convicted of losing his ship might not be punished by imprisonment, dishonorable discharge, or losing his rank - McVey lost his seniority as a captain.
On 29 August 1916 the US Navy cruiser Memphis was anchored in the harbor of Santo Domingo when the waves got rough. Captain Edward L. Beach Sr. ordered the hours-long process of firing up the boilers so the ship could steam out to deeper waters. Before the ship could get underway giant waves struck it and smashed into rocks at the edge of the harbor. 43 sailors were dead or missing and 204 seriously injured.
Captain Beach was convicted of not having enough steam to get his ship underway at short notice. Because of the theory that the giant waves were an unpredictable tsunami, Captain Beach's punishment was restricted to being moved 20 places back on the seniority list, which the secretary of the Navy reduced to being moved back 5 places.
Captain Beach later commanded the naval torpedo squadron at Newport Rhode Island, the battleship New York and the Mare Island Naval Shipyard.
Modern oceanographers believe the giant waves that destroyed the Memphis were waves from a passing hurricane and thus more predicable.
In any case, captain Beach was convicted of losing his ship in peacetime but retain his rank of captain and continued to command ships.
So it is possible for a captain to be coutmartialed for the loss of his ship and to be acquitted, and as these examples from the US Navy show, it is possible for a convicted captain to retain his rank and even to command a ship again.