def execute(self, statement, params=None, noresult=False): """Execute a statement with the given parameters. @type statement: L{Expr} or C{str} @param statement: The statement to execute. It will be compiled if necessary. @param noresult: If True, no result will be returned. @raise ConnectionBlockedError: Raised if access to the connection has been blocked with L{block_access}. @raise DisconnectionError: Raised when the connection is lost. Reconnection happens automatically on rollback. @return: The result of C{self.result_factory}, or None if C{noresult} is True. """ if self._closed: raise ClosedError("Connection is closed") if self._blocked: raise ConnectionBlockedError("Access to connection is blocked") if self._event: self._event.emit("register-transaction") self._ensure_connected() if isinstance(statement, Expr): if params is not None: raise ValueError("Can't pass parameters with expressions") state = State() statement = self.compile(statement, state) params = state.parameters statement = convert_param_marks(statement, "?", self.param_mark) raw_cursor = self.raw_execute(statement, params) if noresult: self._check_disconnect(raw_cursor.close) return None return self.result_factory(self, raw_cursor)
def _ensure_connected(self): """Ensure that we are connected to the database. If the connection is marked as dead, or if we can't reconnect, then raise DisconnectionError. """ if self._blocked: raise ConnectionBlockedError("Access to connection is blocked") if self._state == STATE_CONNECTED: return elif self._state == STATE_DISCONNECTED: raise DisconnectionError("Already disconnected") elif self._state == STATE_RECONNECT: try: self._raw_connection = self._database.raw_connect() except DatabaseError as exc: self._state = STATE_DISCONNECTED self._raw_connection = None raise DisconnectionError(str(exc)) else: self._state = STATE_CONNECTED