Close cursor in query_db
Use row_factory for efficient db access
Fix redirection
Use context manager for query_db