5. Regarding the set
$$
S=\left\{n \mid n \in \mathbf{Z}, \text { and } \frac{n^{3}+n^{2}+n+1}{3 n^{2}+7 n-1} \in \mathbf{Z}\right\}
$$

the correct statement about the number of elements $|S|$ is ( ).
(A) $|S|=2$
(B) $|S|=3$
(C) $|S|=4$
(D) $S$ is a finite set, and $|S| \geqslant 5$
5.B.

Consider the following three cases.
(1) Clearly, $n=0$ satisfies the condition.
(2) When $n>0$,
$$
\begin{array}{l}
\frac{n^{3}+n^{2}+n+1}{3 n^{2}+7 n-1} \in \mathbf{Z} \\
\Leftrightarrow \frac{n^{3}+n^{2}+n+1}{3 n^{2}+7 n-1}+1 \in \mathbf{Z} \\
\quad \Leftrightarrow \frac{n\left(n^{2}+4 n+8\right)}{3 n^{2}+7 n-1} \in \mathbf{Z} \\
\quad \Leftrightarrow \frac{n^{2}+4 n+8}{3 n^{2}+7 n-1} \in \mathbf{Z}\left(\left(n, 3 n^{2}+7 n-1\right)=1\right) \\
\quad \Rightarrow 3 n^{2}+7 n-1 \leqslant n^{2}+4 n+8 \Rightarrow n=1 .
\end{array}
$$

However, $n=1$ does not satisfy the given condition.
(3) When $n<0$, let $n_{1}=-n$ (where $n_{1}>0$), then similarly we get
$$
\frac{n^{2}+4 n+8}{3 n^{2}+7 n-1} \in \mathbf{Z} \Leftrightarrow \frac{n_{1}^{2}-4 n_{1}+8}{3 n_{1}^{2}-7 n_{1}-1} \in \mathbf{Z} .
$$

Clearly, when $n_{1}=1$, it satisfies the condition;
When $n_{1}=2$, it does not satisfy the given condition;
When $n_{1} \geqslant 3$, both the numerator and the denominator of equation (1) are greater than 0, so, $3 n_{1}^{2}-7 n_{1}-1 \leqslant n_{1}^{2}-4 n_{1}+8$, i.e., $\left(2 n_{1}+3\right)\left(n_{1}-3\right) \leqslant 0$.
Thus, $n_{1}=3$ satisfies the condition.
In summary, $S=\{0,-1,-3\}$, hence $|S|=3$.