nodejs插入postgresql表

ljo96ir5  于 2023-08-04  发布在  PostgreSQL
关注(0)|答案(1)|浏览(117)

我正在尝试插入随机数据(大小必须为250K)到表中。下面是我表模式DDL:第一个月
下面是我的代码:

'use strict';

var pg  = require('pg');
var randomBytes = require('randombytes');

var pool = new pg.Pool({
 host     : 'xxx',
 user     : 'postgres',
 password : 'xxxx',
 database : 'mydb',
 max:20,
 idleTimeoutMillis: 3000,
});

async function run(){

 for (let i=0; i<100000; i++){

 await new Promise(done => setTimeout(done, 100));
 await pool.connect(function (error, connection) {
   if (error) throw error;
   connection.query('insert into entries(content) values($1)', [randomBytes(8)+Buffer.alloc(249992,1)], function (error, results, fields) {
     if (error) throw error;
     connection.release();
     console.log("Current row "+ i + "!");
   });
 });
}
}
run();

字符串
每次我运行代码,在服务器轮之后,它都出错,如infor:error: invalid byte sequence for encoding "UTF8": 0x00 or error: invalid input syntax for type bytea
以下是env信息:psql (13.11 (Debian 13.11-0+deb11u1), server 14.7) SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
我在mysql中运行类似的代码(用mediumblob)就可以了。如何在postgresql中运行

kdfy810k

kdfy810k1#

使用此代码,此代码使用Buffer.concat()正确构造内容缓冲区,并使用pool.connect()回调中的async/await正确处理异步连接;

'use strict';

var pg = require('pg');
var randomBytes = require('randombytes');

var pool = new pg.Pool({
    host: 'xxx',
    user: 'postgres',
    password: 'xxxx',
    database: 'mydb',
    max: 20,
    idleTimeoutMillis: 3000,
});

async function run() {
    try {
        for (let i = 0; i < 100000; i++) {
            await new Promise(done => setTimeout(done, 100));

            const content = Buffer.concat([randomBytes(8), Buffer.alloc(249992, 1)]);

            await pool.connect(async (error, connection) => {
                if (error) throw error;

                try {
                    await connection.query('insert into entries(content) values($1)', [content]);
                    console.log("Current row " + i + "!");
                } finally {
                    connection.release();
                }
            });
        }
    } catch (error) {
        console.error("Error:", error);
    } finally {
        pool.end();
    }
}

run();

字符串
请记住将'xxx'、'postgres'、'xxxx'、'mydb'和任何其他连接详细信息替换为PostgreSQL数据库配置的适当值。

相关问题