2017-04-05 5 views
1

私は小さなユーティリティを書いて、あるsqliteデータベースファイルから別のものにデータをコピーしています。どちらのファイルも同じテーブル構造になっています。node-sqliteを使用してあるDBから別のDBにデータをコピーする - 'insert'文をフォーマットする

マイコード:

let tables: Array<string> = [ 
     "OneTable", "AnotherTable", "DataStoredHere", "Video" 
    ] 

tables.forEach((table) => { 
    console.log(`Copying ${table} table`); 

    sourceDB.each(`select * from ${table}`, (error, row) => { 
     console.log(row); 
     destDB.run(`insert into ${table} values (?)`, ...row) // this is the problem 
    }) 
}) 

rowここでは、各テーブルからすべてのキー付きのデータで、jsオブジェクトです。私は、ストリング化されたデータをエスケープすることを伴わない簡単な方法があることは確かです。

答えて

1

動的に生成されたパラメータと参照を使用して、rowsetupのクエリを反復することができます。

let tables: Array<string> = [ 
     "OneTable", "AnotherTable", "DataStoredHere", "Video" 
    ] 

tables.forEach((table) => { 
    console.log(`Copying ${table} table`); 

    sourceDB.each(`select * from ${table}`, (error, row) => { 
     console.log(row); 
     const keys = Object.keys(row); // ['column1', 'column2'] 
     const columns = keys.toString(); // 'column1,column2' 
     let parameters = {}; 
     let values = ''; 

     // Generate values and named parameters 
     Object.keys(row).forEach((r) => { 
      var key = '$' + r; 
      // Generates '$column1,$column2' 
      values = values.concat(',', key); 
      // Generates { $column1: 'foo', $column2: 'bar' } 
      parameters[key] = row[r]; 
     }); 

     // SQL: insert into OneTable (column1,column2) values ($column1,$column2) 
     // Parameters: { $column1: 'foo', $column2: 'bar' } 
     destDB.run(`insert into ${table} (${columns}) values (${values})`, parameters); 
    }) 
}) 
1

データベースドライバがATTACHをブロックしていない場合、あなたは、単にすべてをコピーするには、データベースを伝えることができます。

ATTACH '/some/where/source.db' AS src; 
INSERT INTO main.MyTable SELECT * FROM src.MyTable; 
関連する問題