如何防止在 mySQL 中输入包含空格的文本

How to prevent entering text containing spaces in mySQL

偶尔会发生用户错误地在文本列中输入尾随 space 的文本,这种情况很难通过视觉发现。当此文本字段必须与尾随 space 不存在的另一个文本字段匹配时,这可能会在以后导致问题。是否可以在 mySQL 中强制文本字符串不能包含特定字符(在本例中为 space)?

感谢您的反馈!

有多种方法可以实现您想要的:

  1. 检查应用程序中的用户输入,如果包含 space,则拒绝输入。如果您主要担心用户输入的质量,那么这可能是最好的方法。

  2. 您可以在应用程序逻辑中或使用 sql 从用户输入中删除 spaces(或只是开始/尾随 spaces)。 =11=]

如果您选择从 sql 中的用户输入中删除所有 space,则使用 replace() function. If you just want to remove the starting and trailing spaces, then use the trim() function 来获得所需的结果。

使用mysql函数的一种简单方法是基于trim()

select 
  trim('    try with trim  ')
, length (trim('    try with trim  '))
, length ('    try with trim  ') 
from dual ;