使用nodejs将CSV文件导入mysql数据库
Posted
技术标签:
【中文标题】使用nodejs将CSV文件导入mysql数据库【英文标题】:import CSV file into mysql database using nodejs 【发布时间】:2021-12-30 02:04:17 【问题描述】:我正在尝试使用 nodejs 将 CSV 文件上传到 mysql 数据库...它工作成功并添加了行,但它给了我一个错误。 这是我的代码:
//use express static folder
app.use(express.static("./public"))
// body-parser middleware use
app.use(bodyParser.json())
app.use(bodyParser.urlencoded(
extended: true
))
db.connect(function (err)
if (err)
return console.error('error: ' + err.message);
console.log('Connected to the MySQL server.');
)
//! Use of Multer
var storage = multer.diskStorage(
destination: (req, file, callBack) =>
callBack(null, './uploads/')
,
filename: (req, file, callBack) =>
callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
)
var upload = multer(
storage: storage
);
//! Routes start
//route for Home page
app.get('/', (req, res) =>
res.sendFile(__dirname + '/index.html');
);
// upload csv to database
app.post('/uploadfile', upload.single("uploadfile"), (req, res) =>
UploadCsvDataToMySQL(__dirname + '/uploads/' + req.file.filename);
console.log('CSV file data has been uploaded in mysql database ' + err);
);
function UploadCsvDataToMySQL(filePath)
let stream = fs.createReadStream(filePath);
let csvData = [];
let csvStream = csv
.parse()
.on("data", function (data)
csvData.push(data);
)
.on("end", function ()
// Remove Header ROW
csvData.shift();
// Open the MySQL connection
db.connect((error) =>
if (error)
console.error(error);
else
let query = 'INSERT INTO files (File_ID, File_Name) VALUES ?';
db.query(query, [csvData], (error, response) =>
console.log(error || response);
);
);
// delete file after saving to MySQL database
// -> you can comment the statement to see the uploaded CSV file.
fs.unlinkSync(filePath)
);
stream.pipe(csvStream);
//create connection
const PORT = process.env.PORT || 8000
app.listen(PORT, () => console.log(`Server is running at port $PORT`))
这是上传文件后在 PowerShell 中出现的错误:
ReferenceError: 错误未定义 在 C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\index.js:79:72 在 Layer.handle [as handle_request] (C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\express\lib\router\layer.js:95:5) 在下一个(C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\express\lib\router\route.js:137:13) 在阵列。 (C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\multer\lib\make-middleware.js:53:37) 在侦听器处(C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\on-finished\index.js:169:15) 在 onFinish (C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\on-finished\index.js:100:5) 在回调时(C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\ee-first\index.js:55:10) 在 IncomingMessage.onevent (C:\Users\DELL\Desktop\Advanced\AdvancedSeE\dbmanager\node_modules\ee-first\index.js:93:5) 在 IncomingMessage.emit (节点:事件:341:22) 在 endReadableNT(节点:内部/流/可读:1294:12) 结果集标题 字段计数:0, 受影响的行数:3, 插入ID:33333, 信息:'记录:3重复:0警告:0', 服务器状态:2, 警告状态:0
【问题讨论】:
请在提问前阅读您的错误信息。 【参考方案1】:在以下区域中,您在文件中未定义的控制台日志中添加了err
// upload csv to database
app.post('/uploadfile', upload.single("uploadfile"), (req, res) =>
UploadCsvDataToMySQL(__dirname + '/uploads/' + req.file.filename);
console.log('CSV file data has been uploaded in mysql database ' + err); //<----- here err is not defined
);
只要删除这个,如果问题解决了再试试
【讨论】:
以上是关于使用nodejs将CSV文件导入mysql数据库的主要内容,如果未能解决你的问题,请参考以下文章
MYSQL 使用 LOAD DATA INFILE 从 csv 导入数据