varchar vs text - MySQL

て烟熏妆下的殇ゞ 提交于 2019-12-30 10:38:09

问题


in my project an user can write comment [plain text], and view others comment, can delete own comment, but can not update comment !
In this case which would should i use ?

Text or Varchar(4048) ?
What is the advantage and disadvantage of Text and Varchar(large like 4000) ?
Is it secure enough if i replace only '<' with '& lt;' and '>' with '& gt;' to make sure everything is fine ?
[i dont want to convert all those like ' " & ..., to save space, i just want to make sure user can not write javascript]

There will be a limit on the front end


回答1:


To protect yourself from XSS attack, encode it using the htmlentities function.

Other than that, the choice of datatype has most to do with how big the content will be. If it may exceed 4048 characters, then use a text datatype. If many posts will be large, using a text datatype may reduce wasted data space and may perform slightly better than a giant varchar, but it depends upon your situation, you would be best to test the alternatives.

I generally prefer varchar because it's easier to deal with from a coding perspective, if nothing else, and fall back to text if the contents may exceed the size of a varchar.




回答2:


Varchar is usually faster in retrieval when the size is reasonable, as it is stored within the table, where as TEXT is stored off the table with a pointer to location.

Thanks




回答3:


(You have multiple questions; I will address the one that is in the title.)

The only difference between VARCHAR(4000) and TEXT is that an INSERT will truncate to either 4000 characters or 65536 bytes, respectively.

For smaller values than 4000, there are cases where the temp table in a complex SELECT will run faster with, for example, VARCHAR(255) than TINYTEXT. For that reason, I feel that one should never use TINYTEXT.




回答4:


it depends on the application behavior. space allocated inside block's table decrease space for other columns and decrease density data inside it. if full table scan is used by mysql, many blocks are scanned, it's inefficient. so it depends on your sql requests.



来源:https://stackoverflow.com/questions/5739172/varchar-vs-text-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!