如何从node.js中的mysql获取带有位类型字段的行?

Ser*_*giy 6 mysql node.js

我正在使用mysql npm包进行连接并尝试从表中获取数据,该表具有类型为BIT的列.但这些专栏已经变为:

"isBasic": {
      "type": "Buffer",
      "data": [
        1
      ]
    },
Run Code Online (Sandbox Code Playgroud)

如何将它们映射到布尔类型?

小智 10

这可能会晚一些,但是有一种方法可以在定义连接(或池)时将 BIT 字段转换为布尔值:

var pool = mysql.createPool({
    "connectionLimit": process.env.MYSQL_LIMIT,
    "user": process.env.MYSQL_USER,
    "password": process.env.MYSQL_PASSWORD,
    "database": process.env.MYSQL_DATABASE,
    "host": process.env.MYSQL_HOST,
    "port": process.env.MYSQL_PORT,
    "typeCast": function castField( field, useDefaultTypeCasting ) {

        // We only want to cast bit fields that have a single-bit in them. If the field
        // has more than one bit, then we cannot assume it is supposed to be a Boolean.
        if ( ( field.type === "BIT" ) && ( field.length === 1 ) ) {

            var bytes = field.buffer();

            // A Buffer in Node represents a collection of 8-bit unsigned integers.
            // Therefore, our single "bit field" comes back as the bits '0000 0001',
            // which is equivalent to the number 1.
            return( bytes[ 0 ] === 1 );

        }

        return( useDefaultTypeCasting() );
    }
});
Run Code Online (Sandbox Code Playgroud)

这是改编自这篇文章:https://www.bennadel.com/blog/3188-casting-bit-fields-to-booleans-using-the-node-js-mysql-driver.htm


小智 5

bit 数据类型在 mysql 包中没有完美使用。我们通常在表中使用 tinyint 来存储 0 和 1,然后在 Javscript 中进行比较以确定真假。


Luk*_*kas 5

以下是读取 type=BIT 值的方法:

bit.lastIndexOf(1) !== -1
Run Code Online (Sandbox Code Playgroud)

我已经用 true 和 false 值进行了测试:

console.log(bit, ' ----> ', bit.lastIndexOf(1) !== -1);
console.log(bit, ' ----> ', bit.lastIndexOf(1) !== -1);

// out:   <Buffer 01> ' ----> ' true
// out:   <Buffer 00> ' ----> ' false
Run Code Online (Sandbox Code Playgroud)

一种方法是在 SQL 查询中添加转换:

mysql_connection.query('SELECT *,field_name=1 as field_name ...
Run Code Online (Sandbox Code Playgroud)

如果 true 则 field_name 的值为 1,如果 false 则为 0。