Fixing Sql query connection logic