4

I have an array of integers from 0 to 255 in javascript;

var arr = [249, 13, 105, 170];

And it's required to store this data in mysql database according this rule:

  • 1 number = 1 byte

So, if the array length equals 4, then the size of blob data in mysql DB must be 4 bytes. And it works fine with numbers less than 128.

var res = "";    
for(var i = 0; i < arr.length; i++) {
    res += String.fromCharCode(arr[i]);
}

But numbers from 128 to 256 takes 2 bytes.

I tried to use nodejs buffer

var Buffer = require('buffer').Buffer,
    buf = new Buffer(arr.length);
for(var i = 0; i < arr.length; i++) {
    buf[i] = arr[i];
}
buf.toString('binary');

but the same result. I have no idea how to make it work.

to store data in mysql database I use node-mysql

var Client = require('mysql').Client,
    client = new Client();
client.user = DB_USER;
client.password = DB_PASS;
client.host = DB_HOST;
client.connect(function(error, results) {
    if(error) {
        client.end();
        return;
    }
    client.query('USE ' + DB_SCHEME, function(error, results) {
        if(error) {
            client.end();
            return;
        }

        var sql = "INSERT INTO b SET `data` = ?";
        var values = [buf];

        client.query(sql, values,
            function(error, results) {
                if(error) {
                    return;
                }
                return;
            }
        );
    });
});

Do you have any idea?

1 Answer 1

2

I've managed to do it using built-in mysql CHAR function:

var arr = [249, 13, 105, 170];
var sql = "INSERT INTO b SET `data` = CHAR( " + arr + " )";

client.query(sql);

where data is blob data

Sign up to request clarification or add additional context in comments.

2 Comments

can u plz tell the same for prepared statement
I got an error: ER_TRUNCATED_WRONG_VALUE: Truncated incorrect INTEGER

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.