在JavaScript中顺序运行SQL函数

jaql4c8m  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(93)

似乎这个问题已经得到了回答here,然而,我不知道如何使它工作,因为我仍然是新的JavaScript。
我尝试过在DuckDB和Sqlite3中使用Node.js。两者都不能像预期的那样工作。下面是我的代码:data2.js

// data2.js
const fs = require('fs');
// const sql = require('sqlite3');
const sql = require('duckdb');
const csvParser = require('csv-parser');
const stream = require('stream');

// CSV data as a string
const csvData = `Wind speed (m/s),Output power (kW)
0,0
1,0
2,0
3,0
4,80
5,140
6,360
7,610
8,1000
9,1470
10,1900
11,2320
12,2690
13,2850
14,2950
15,3000
16,3000
17,3000
18,3000
19,3000
20,3000
21,3000
22,3000
23,3000
24,3000
25,3000`;

// Function to create a database, table, and insert data
function createAndStoreData() {
  console.log('createAndStoreData()');
  const db = new sql.Database('power_curve.db');

  db.serialize(() => {
    db.run('DROP TABLE IF EXISTS power_curve');
    db.run('CREATE TABLE IF NOT EXISTS power_curve (ws DECIMAL PRIMARY KEY, power DECIMAL)');

    const stmt = db.prepare('INSERT INTO power_curve VALUES (?, ?)');

    const dataStream = new stream.Readable();
    dataStream.push(csvData);
    dataStream.push(null);

    dataStream
      .pipe(csvParser())
      .on('data', (row) => {
        stmt.run(row['Wind speed (m/s)'], row['Output power (kW)']);
      })
      .on('end', () => {
        stmt.finalize();
        db.close((err) => {
          if (err) {
            return console.error('Error closing database:', err.message);
          }
          console.log('Data stored in power_curve.db successfully.');
        });
      })
      .on('error', (error) => {
        console.error('Error reading CSV data:', error.message);
      });
  });
}

// Function to read data from the database
function readData() {
  console.log('readData()');
  const db = new sql.Database('power_curve.db');

  db.serialize(() => {
    db.all('SELECT * FROM power_curve', (err, rows) => {
      if (err) {
        console.error('Error querying data:', err.message);
      } else {
        console.table(rows);
        console.log('Data read from power_curve.db successfully.');
      }

      db.close((err) => {
        if (err) {
          console.error('Error closing database:', err.message);
        }
      });
    });
  });
}

if (require.main === module) {
  createAndStoreData();
  readData();
}

字符串
第一次运行代码时,将给予以下消息:

node data2.js
createAndStoreData()
readData()
Error querying data: Connection Error: Connection was never established or has been closed already
Error closing database: Database was already closed
Data stored in power_curve.db successfully.

的数据
第二次运行它时,我会得到以下消息:

node data2.js
createAndStoreData()
readData()
Error closing database: Database was already closed
┌─────────┬────┬───────┐
│ (index) │ ws │ power │
├─────────┼────┼───────┤
│    0    │ 0  │   0   │
│    1    │ 1  │   0   │
│    2    │ 2  │   0   │
│    3    │ 3  │   0   │
│    4    │ 4  │  80   │
│    5    │ 5  │  140  │
│    6    │ 6  │  360  │
│    7    │ 7  │  610  │
│    8    │ 8  │ 1000  │
│    9    │ 9  │ 1470  │
│   10    │ 10 │ 1900  │
│   11    │ 11 │ 2320  │
│   12    │ 12 │ 2690  │
│   13    │ 13 │ 2850  │
│   14    │ 14 │ 2950  │
│   15    │ 15 │ 3000  │
│   16    │ 16 │ 3000  │
│   17    │ 17 │ 3000  │
│   18    │ 18 │ 3000  │
│   19    │ 19 │ 3000  │
│   20    │ 20 │ 3000  │
│   21    │ 21 │ 3000  │
│   22    │ 22 │ 3000  │
│   23    │ 23 │ 3000  │
│   24    │ 24 │ 3000  │
│   25    │ 25 │ 3000  │
└─────────┴────┴───────┘
Data read from power_curve.db successfully.
wwwo4jvm

wwwo4jvm1#

我自己使用asyncawait为sqlite3修复了它。然而,duckdb似乎有不同的行为。

const sql = require('sqlite3');
//const sql = require('duckdb');
const csvParser = require('csv-parser');
const stream = require('stream');

// CSV data as a string
const csvData = `Wind speed (m/s),Output power (kW)
0,0
1,0
2,0
3,0
4,80
5,140
6,360
7,610
8,1000
9,1470
10,1900
11,2320
12,2690
13,2850
14,2950
15,3000
16,3000
17,3000
18,3000
19,3000
20,3000
21,3000
22,3000
23,3000
24,3000
25,3000`;

// Function to create a database, table, and insert data
async function createAndStoreData() {
  console.log('createAndStoreData()');
  const db = new sql.Database('power_curve.db');

  return new Promise((resolve, reject) => {
    db.serialize(() => {
      db.run('DROP TABLE IF EXISTS power_curve');
      db.run('CREATE TABLE IF NOT EXISTS power_curve (ws DECIMAL PRIMARY KEY, power DECIMAL)');

      const stmt = db.prepare('INSERT INTO power_curve VALUES (?, ?)');

      const dataStream = new stream.Readable();
      dataStream.push(csvData);
      dataStream.push(null);

      dataStream
        .pipe(csvParser())
        .on('data', (row) => {
          stmt.run(row['Wind speed (m/s)'], row['Output power (kW)']);
        })
        .on('end', () => {
          stmt.finalize();
          db.close((err) => {
            if (err) {
              reject(err);
            } else {
              console.log('Data stored in power_curve.db successfully.');
              resolve();
            }
          });
        })
        .on('error', (error) => {
          reject(error);
        });
    });
  });
}

// Function to read data from the database
async function readData() {
  console.log('readData()');
  const db = new sql.Database('power_curve.db');

  return new Promise((resolve, reject) => {
    db.serialize(() => {
      db.all('SELECT * FROM power_curve', (err, rows) => {
        if (err) {
          reject(err);
        } else {
          console.table(rows);
          console.log('Data read from power_curve.db successfully.');
          resolve();
        }

        db.close((err) => {
          if (err) {
            reject(err);
          }
        });
      });
    });
  });
}

async function main() {
  try {
    await createAndStoreData();
    await readData();
  } catch (error) {
    console.error('Error:', error.message);
  }
}

if (require.main === module) {
  main();
}

字符串
我在https://github.com/duckdb/duckdb-wasm/discussions/1484中提交了一个讨论主题,如果你热衷于跟进的话。

相关问题