bulk insert using CSV file #1842
-
To initialize DB using CSV file, I'm trying bulk import like issue #830 . import { Connection, createConnection } from 'mysql2/promise'
import * as fs from 'fs'
import * as csvSync from 'csv-parse/lib/sync'
type Table = {
name: string,
idColumnName: string
}
await function insert(filePath: string, table: Table): Promise<void> {
const connection = createConnection({ host, port, user, password, database })
const data: any[][] = csvSync(fs.readFileSync(filePath, 'utf-8'), {
cast: (value, _) => (value.toLowerCase() === 'null' ? null : value),
})
const query = `INSERT INTO ${table.name} VALUES (?) ON DUPLICATE KEY UPDATE ${table.idColumnName}=${table.idColumnName}`
// it doesn't work well
await connection.query(query, data)
// it works, but I feel it's verbose
// await Promise.all(csv.data.map(row => connection.query(query, [row])))
} As a result, only 1st record of the CSV file inserted into DB. I put the data to array: await connection.query(query, [data]) It become error. 'sql' has unnecessary brackets.
For trial: await connection.query(query, data.map(row => [row])) and then, error was:
The 1st record only was tried to insert (and failed). How can I insert CSV file without shredding? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
$ node -v
v19.6.0 |
Beta Was this translation helpful? Give feedback.
-
The easiest way to figure out how client side interpolation works is to simplify your example and 1) factor out CSV parsing ( just copy couple of rows of data and have them hardcoded and 2) factor out db communication. you can just use If you can paste your starting point with hardcoded data and sql query I can try to help you along |
Beta Was this translation helpful? Give feedback.
The easiest way to figure out how client side interpolation works is to simplify your example and 1) factor out CSV parsing ( just copy couple of rows of data and have them hardcoded and 2) factor out db communication. you can just use
console.log(mysql.escape('sql, parameters))
for quicker iterations - play around until you get the correct valid sql syntaxIf you can paste your starting point with hardcoded data and sql query I can try to help you along