Edited counting query and db connection exception