Automatically trimming length of string submitted to MySQL

后端 未结 4 1763
南笙
南笙 2020-12-11 04:51

When I submit a form field to a mySQL database is there a way to set the database to automatically discard any data in excess of the data field length?

I know I can

4条回答
  •  旧时难觅i
    2020-12-11 05:28

    You mean you want to set this in a data definition script for example when creating a table? According to the documentation you can't do this. Perhaps you could use a trigger to handle data before it is inserted? Something like this (I can not garantuee that the code below actually works):

    CREATE TRIGGER chopdata BEFORE INSERT ON mytable
      FOR EACH ROW BEGIN
        NEW.myfield = SELECT SUBSTRING(NEW.myfield,1,20)
      END;
    

    Else you can chop out the maximum length by using substring straight in your query/procedure:

    SELECT SUBSTRING('your very long string goes here',1,20);
    

提交回复
热议问题