【问题标题】:How do I insert a blob into mysql using typescript / mysql package如何使用 typescript / mysql 包将 blob 插入 mysql
【发布时间】:2021-08-31 22:47:21
【问题描述】:

我很惊讶我没有找到更多关于这个的答案。 我正在尝试使用 javascript/typescript 和 mysql 包使用以下代码插入 blob:

import mysql, {Connection} from 'mysql';
import {readFileSync} from "fs";

const NAME = 'GMDev';
const HOST = 'localhost';
const PORT = 3306;
const USER = 'gm_dev';
const PASSWD = 'secret';

const db = mysql.createConnection({
    host: HOST,
    user: USER,
    password: PASSWD,
    database: NAME
});

function query(db: Connection, sql: string, data?: any): Promise<any> {
    return new Promise((resolve, reject) => {
        db.query(sql, data, (err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        })
    })
}

let sql = '';
const imgData = readFileSync('./test.png');
console.log(`buffer length: ${imgData.length}`);
sql = "INSERT INTO image (type,image) VALUES('product',BINARY (?))";
const data = {image: imgData};
let result = query(db, sql, data).then((result) => {
    console.log(`result: ${JSON.stringify(result)}`);
}).then(() => {
    sql = 'SELECT * FROM image';
    return query(db, sql);
}).then((result) => {
    console.log(`result: ${JSON.stringify(result)}`);
}).catch((err) => {
    console.log(`Error ${err}`);
});

数据库表如下:

create table image
(
    id    int auto_increment primary key,
    type  enum ('product', 'card', 'other') null,
    image blob not null
);

我的小测试程序的输出是这样的:

buffer length: 336922
result: {"fieldCount":0,"affectedRows":1,"insertId":5,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
result: [{"id":5,"type":"product","image":{"type":"Buffer","data":[48]}}]

含义: 我的缓冲区长 336922 字节,插入了一行,但 blob 只包含一个字节。

有什么想法吗?

托马斯干杯

【问题讨论】:

    标签: javascript mysql typescript blob


    【解决方案1】:

    找到了。 对于初学者,我不知道我从哪里得到的:

    const data = {image: imgData};
    

    当我使用对象数组时,它可以工作.. 此外,BLOB 实际上无法获取我尝试插入的数据大小,至少在 MariaDB(我正在使用)上我需要使用 MEDIUMBLOB。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-15
      • 2015-11-03
      • 2021-02-17
      • 1970-01-01
      • 2019-09-25
      • 2018-04-19
      相关资源
      最近更新 更多