Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql insert statement to binary datatype?

Tags:

sql

mysql

I am using MySQL database.

I have one table having column with datatype binary(16).

I need help with the insert statement for this table.

Example:
CREATE TABLE `assignedresource` (
`distid` binary(16) NOT NULL
)

insert into assignedresource values ('9fad5e9e-efdf-b449');

Error : Lookup Error - MySQL Database Error: Data too long for column 'distid' at row 1

How to resolve this issue?

like image 461
Dhruv Bansal Avatar asked Jan 31 '12 14:01

Dhruv Bansal


People also ask

How do I query binary in MySQL?

The MySQL BINARY function is used for converting a value to a binary string. The BINARY function can also be implemented using CAST function as CAST(value AS BINARY). The BINARY function accepts one parameter which is the value to be converted and returns a binary string.

What is binary data type in MySQL?

The BINARY attribute is a nonstandard MySQL extension that is shorthand for specifying the binary ( _bin ) collation of the column character set (or of the table default character set if no column character set is specified). In this case, comparison and sorting are based on numeric character code values.

What is the difference between binary and Varbinary?

binary [ ( n ) ] Fixed-length binary data with a length of n bytes, where n is a value from 1 through 8,000. The storage size is n bytes. varbinary [ ( n | max) ] Variable-length binary data. n can be a value from 1 through 8,000.

How manually insert data in MySQL table?

MySQL INSERT INTO – General SyntaxINSERT INTO table_name(column_1,column_2,column_3) VALUES (value_1,value_2,value_3); In the INSERT INTO query, you should specify the following information: table_name : A MySQL table to which you want to add a new row.


2 Answers

You should remove the hyphens to make the value match the length of the field...

Example:
CREATE TABLE `assignedresource` (
`distid` binary(16) NOT NULL
)

insert into assignedresource values ('9fad5e9eefdfb449');

Also, MySQL standard is to use this notation to denote the string as binary... X'9fad5e9eefdfb449', i.e.

insert into assignedresource values (X'9fad5e9eefdfb449');
like image 170
Rik Smith-Unna Avatar answered Sep 19 '22 09:09

Rik Smith-Unna


Well, assuming that you want to strictly insert a hexadecimal string, first you need to remove the dashes and then "unhex" your string before inserting it into a binary(16) data type column, the code would go like this:

INSERT INTO `assignedresource` VALUES(UNHEX(REPLACE('9fad5e9e-efdf-b449','-','')));

Also... the "usable" data you are inserting is actually 8 bytes after undashing it, so binary(8) would do fine if you plan on not storing the dashes.

like image 25
Xedret Avatar answered Sep 22 '22 09:09

Xedret