Improve SQL error handling