开发者

What is the best datatype for storing URLs in a MySQL database?

What is the best datatype for storing URLs in a MySQL database?

The ideal would be something that doesn't take up a lot of sp开发者_如何学运维ace but can easily handle variable length URLs.


If by "links" you mean links to web pages, I'm guessing you want to store URLs.

Since URLs are variable length strings the VARCHAR data type would seem the obvious choice.


You can store URLs as simple strings, but be careful when comparing values since URLs may come in various forms while actually representing the same location (for example with/without the initial protocol identifier, or with/without a trailing slash).


We can also take BLOB datatype in mysql Database for URL and file link


We can use both Varchar(255) or BLOB. URL stored in text format in the database.


I recommend a VARCHAR field and the length is really personal opinion on what kind of URLs you are anticipating storing. You can get away with VARCHAR(255) without increasing the storage requirements for a VARCHAR field without penalty.

CREATE TABLE example(
    id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    url varchar(125)  
);

$url = 'http://www.google.com';
$sql = 'INSERT INTO example SET url = ' . mysql_real_escape_string($url);


As the length of the web URL for different websites and pages are different thus it is appropriate to use data type with varying length.

e.g if we want to store "www.google.com" in our database it will not be a problem but if we want to save link for search result from google like

"https://www.google.com/search?newwindow=1&safe=active&ei=nc1SXYS2EfvKgwfmkYsQ&q=Allah&oq=Allah&gs_l=psy-ab.3..0i71l8.65605.66784..67313...0.0..0.0.0.......6....1..gws-wiz.j8DsXUL6juY&ved=0ahUKEwjE-LTPi4DkAhV75eAKHebIAgIQ4dUDCAo&uact=5"

than we will need lots of space for that.

If you construct a CHAR field large enough to hold this URL, you will be wasting a significant amount of space for almost every other URL being stored. A variable-length field lets you define a field length that can store the odd, long-length value while not wasting all that space for the common, short-length values. Variable-length text fields in MySQL use only as much space as necessary to store an individual value into the field.

A VARCHAR(255) field that holds the string "www.google.com" for example, takes up only 15 bytes (1 byte for each character plus an extra byte to store the length). TIP: MySQL varies from the ANSI standard by not padding VARCHAR fields. Any extra spaces are removed from a value before it is stored.


If you want to follow the maximum length of 2,048 characters:

VARCHAR(2048)

Such as:

CREATE TABLE new_table (
`id` INT UNSIGNED NOT NULL,
web_url VARCHAR(2048) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜