Home > Article > Web Front-end > Node.js massively injects data into MySQL
This time I will bring you Node.jsInjecting a large amount of data into MySQL, Node.js injecting a large amount of data into MySQL. What are the things to note?The following are practical cases, one Get up and take a look.
1. Database connection
var mysql = require('mysql'); // 数据库信息 var connection = mysql.createConnection({ host : 'localhost', user : '数据库用户名', password : '数据库登录密码', database : '操作数据库名' });Convert
insert data into nested array
For example, two pieces of data to be inserted: Record 1:from:"index" to:“www.alibaba.com” status:1 is_new:0Record 2:
from:"index1" to:"www.google.com" status:1 is_new:0Convert to the following format:
var values = [ ["index","www.alibaba.com",1,0], ["index1","www.google.com",1,0] ];Write insert statement
var sql = "INSERT INTO url(`from`,`to`,`status`, `is_new`) VALUES ?";Call the query function to complete the data insertion
connection.query(sql, [values], function (err, rows, fields) { if(err){ console.log('INSERT ERROR - ', err.message); return; } console.log("INSERT SUCCESS"); });Complete code:
var mysql = require('mysql'); // 数据库信息 var connection = mysql.createConnection({ host : 'localhost', user : '数据库用户名', password : '数据库登录密码', database : '操作数据库名' }); var values = [ ["index","www.alibaba.com",1,0], ["index1","www.google.com",1,0] ]; var sql = "INSERT INTO url(`from`,`to`,`status`, `is_new`) VALUES ?"; connection.query(sql, [values], function (err, rows, fields) { if(err){ console.log('INSERT ERROR - ', err.message); return; } console.log("INSERT SUCCESS"); });At the same time, a transaction-based operation is recorded here (it has not been practiced yet, and the specific effect is unknown) Insert using transaction loop and rollback if an insertion fails mysql module, connection.beginTrans
action is to do transactions
Then I encapsulated a function here to perform operations such as loop insertion or update on the incoming array. If one item fails, roll back, and if everything is correct, commit I believe you have read the case in this article. After mastering the method, please pay attention to other related articles on the php Chinese website for more exciting content! Recommended reading:A detailed explanation of the steps for AngularJS registration form verification
A detailed explanation of the steps to implement the copy function in clipboard.js
The above is the detailed content of Node.js massively injects data into MySQL. For more information, please follow other related articles on the PHP Chinese website!