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, the开发者_高级运维n 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?
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
精彩评论