def query( conn: Connection, sql: str, fetch_mode: FetchMode = FetchMode.ALL, size: int = 1, args: Optional[Union[dict, tuple, list]] = None, ): print(sql.replace("\n", " ").replace(" ", " ")) print(args) conn.ping(True) # Throws QueryKeyError with conn.cursor() as cursor: try: cursor.execute(sql, args) except KeyError as err: raise QueryKeyError(key=err.args[0]) except ProgrammingError as err: print("A Programming error occurs =========") print(sql) print(err.args[0]) print(err.args[1]) print("=================") except InternalError as err: print(sql) print(err.args[0]) if fetch_mode is FetchMode.ONE: return cursor.fetchone() elif fetch_mode is FetchMode.MANY: return cursor.fetchmany(size) elif fetch_mode is FetchMode.ALL: return cursor.fetchall() conn.commit()
def get_connection(self): """Get a connection from the pool This method returns an PooledPyMySQLConnection instance which has a reference to the pool that created it, and the next available MySQL connection. When the MySQL connection is not connect, a reconnect is attempted. Raises PoolError on errors. Returns a PooledPyMySQLConnection instance. """ with CONNECTION_POOL_LOCK: try: cnx = self._cnx_queue.get(block=False) except queue.Empty: raise PoolError("Failed getting connection; pool exhausted") if not is_connected( cnx) or self._config_version != cnx._pool_config_version: cnx = Connection(**self._cnx_config) try: cnx.ping(reconnect=True) except Exception as e: # Failed to reconnect, give connection back to pool self._queue_connection(cnx) raise cnx._pool_config_version = self._config_version return PooledPyMySQLConnection(self, cnx)
def insert_into(conn: Connection, table_name: str, **kwargs: Any) -> Optional[int]: conn.ping(True) keys, values, make_str = get_key_val_lists(**kwargs) result = None try: with conn.cursor() as cursor: cursor.execute( INSERT_INTO.format(table_name, ",".join(keys), make_str), (*values, )) result = cursor.lastrowid except IntegrityError as err: matches = DUPLICATE_KEY_ERROR_PATTERN.match(err.args[1]) if err.args[0] == 1062 and matches is not None: raise QueryDuplicateError(matches.group(3), matches.group(1)) else: raise QueryError(*err.args) except ProgrammingError as err: raise QueryError(*err.args) except OperationalError as err: raise QueryError(*err.args) conn.commit() if result is not None: return result