Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. const path = require('path');
  2. const fs = require('fs');
  3. const csv_parse = require('csv-parse');
  4. const sqlite3 = require('sqlite3').verbose();
  5. const db = new sqlite3.Database(':memory:');
  6.  
  7. function loadDataFile(dataFile, tableName, fileOptions={}) {
  8. const startTime = new Date();
  9.  
  10. // read CSV file
  11. const csvPath = path.join(__dirname, 'data', dataFile);
  12. fs.readFile(csvPath, 'utf8', (err, file_data) => {
  13. if(err)
  14. console.error(err);
  15.  
  16. // parse file data into arrays
  17. csv_parse(file_data, fileOptions, (err, table) => {
  18. if(err)
  19. console.error(err);
  20.  
  21. const colNames = table[0];
  22.  
  23. db.serialize(function () {
  24.  
  25. // create table in database
  26. db.run(`CREATE TABLE ${tableName} ( ${colNames.map(col => col+' TEXT').join(',') })`);
  27.  
  28. // prepare insert statement and run for each row
  29. const placeholders = colNames.map(() => '?').join(',');
  30. const stmt = db.prepare(`INSERT INTO ${tableName} VALUES (${placeholders})`);
  31. for (let row of table.slice(1)) {
  32. stmt.run(row)
  33. }
  34.  
  35. // print row count and elapsed time
  36. const elapsed = (new Date() - startTime)/1000;
  37. db.get(`SELECT COUNT(*) FROM ${tableName}`, (err, res) => {
  38. stmt.finalize(() => console.log(`Loaded ${res['COUNT(*)']} rows into ${tableName} in ${elapsed} seconds`))
  39. });
  40.  
  41. });
  42.  
  43. db.close();
  44. })
  45.  
  46. });
  47.  
  48. }
  49.  
  50. loadDataFile('stock_trades.csv', 'STOCK_TRADES');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement