Execute a query. query -- string, query to execute on server args -- optional sequence or mapping, parameters to use with query. Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)
(self, query, args=None)
| 155 | return self.connection |
| 156 | |
| 157 | def execute(self, query, args=None): |
| 158 | |
| 159 | """Execute a query. |
| 160 | |
| 161 | query -- string, query to execute on server |
| 162 | args -- optional sequence or mapping, parameters to use with query. |
| 163 | |
| 164 | Note: If args is a sequence, then %s must be used as the |
| 165 | parameter placeholder in the query. If a mapping is used, |
| 166 | %(key)s must be used as the placeholder. |
| 167 | |
| 168 | Returns long integer rows affected, if any |
| 169 | |
| 170 | """ |
| 171 | del self.messages[:] |
| 172 | db = self._get_db() |
| 173 | |
| 174 | charset = db.character_set_name() |
| 175 | |
| 176 | if args is not None: |
| 177 | if isinstance(query, bytes): |
| 178 | query = query.decode(); |
| 179 | |
| 180 | if isinstance(args, dict): |
| 181 | query = query.format( **db.literal(args) ) |
| 182 | elif isinstance(args, tuple) or isinstance(args, list): |
| 183 | query = query.format( *db.literal(args) ) |
| 184 | else: |
| 185 | query = query.format( db.literal(args) ) |
| 186 | |
| 187 | if isinstance(query, str): |
| 188 | query = query.encode(charset); |
| 189 | |
| 190 | try: |
| 191 | r = None |
| 192 | r = self._query(query) |
| 193 | except TypeError as m: |
| 194 | if m.args[0] in ("not enough arguments for format string", |
| 195 | "not all arguments converted"): |
| 196 | self.messages.append((ProgrammingError, m.args[0])) |
| 197 | self.errorhandler(self, ProgrammingError, m.args[0]) |
| 198 | else: |
| 199 | self.messages.append((TypeError, m)) |
| 200 | self.errorhandler(self, TypeError, m) |
| 201 | except (SystemExit, KeyboardInterrupt): |
| 202 | raise |
| 203 | except: |
| 204 | exc, value, tb = sys.exc_info() |
| 205 | del tb |
| 206 | self.messages.append((exc, value)) |
| 207 | self.errorhandler(self, exc, value) |
| 208 | self._executed = query |
| 209 | if not self._defer_warnings: self._warning_check() |
| 210 | return r |
| 211 | |
| 212 | def executemany(self, query, args): |
| 213 |