简体   繁体   中英

node-mssql error message when trying to do a bulk insert (While reading current row from host, a premature end-of-message was encountered)

When trying to use the .bulk operation of node-mssql lib in node.js, i'm receiving the message:

While reading current row from host, a premature end-of-message was encountered--an incoming data stream was interrupted when the server expected to see more data. The host program may have terminated. Ensure that you are using a supported client application programming interface (API)
// the problem happens when i call this function
export async function insert(
  transaction: sql.Request,
  data: any[],
) {
  const table = prepare(data);
  return await transaction.bulk(table);
}

function prepare(data: any[]) {
  const table = new sql.Table('dbo.SomeTable');
  table.create = false;
  table.columns.add('MyColumn1', sql.Int, { nullable: false });
  table.columns.add('MyColumn2', sql.Int, { nullable: false });
  table.columns.add('MyColumn3', sql.Int, { nullable: false });

  for (const mov of data) {
    table.rows.add(
      mov.field1,
      mov.field2,
      mov.field3
    );
  }
  return table;
}

After some time searching a solution, I discover that the problem was my data array was empty. I found the solution in this link: https://github.com/tediousjs/tedious/issues/212#issuecomment-628330044

I got a couple of this error before. It happens also when you don't have any row inserted > in the loop. A typical case is that you have columns added, and then you take some array > from other places, and iterate that array to insert row. Sometimes, when the array is empty, no row is inserted, and I'll get this error. So, better to check if the array is empty before execute the bulkload. (by user jianingliu , in Github)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM