Node.js MySQL INSERT INTO查詢用于將一個或多個記錄插入MySQL表。
Node.js MySQL示例,將記錄插入表中
Node.js MySQL示例,將多條記錄插入表中
訪問結(jié)果對象的屬性
//引入mysql模塊
var mysql = require('mysql');
// 創(chuàng)建具有所需詳細(xì)信息的連接變量
var con = mysql.createConnection({
host: "localhost", // 運行mysql的服務(wù)器的IP地址
user: "arjun", // mysql數(shù)據(jù)庫的用戶名
password: "password", // 對應(yīng)的密碼
database: "studentsDB" // 使用指定的數(shù)據(jù)庫
});
// 建立與數(shù)據(jù)庫的連接。
con.connect(function(err) {
if (err) throw err;
// 如果連接成功
con.query("INSERT INTO students (name,rollno,marks) values ('Anisha',12,95)", function (err, result, fields) {
// 如果在執(zhí)行上述查詢時出現(xiàn)任何錯誤,則拋出錯誤
if (err) throw err;
// 如果沒有錯誤,您將得到結(jié)果
console.log(result);
});
});在終端中的Node.js MySQL程序上方運行。
InsertMulIntoExample.js-將多個記錄插入表的示例
//引入mysql模塊
var mysql = require('mysql');
// 創(chuàng)建具有所需詳細(xì)信息的連接變量
var con = mysql.createConnection({
host: "localhost", // 運行mysql的服務(wù)器的IP地址
user: "arjun", // mysql數(shù)據(jù)庫的用戶名
password: "password", // 對應(yīng)的密碼
database: "studentsDB" // 使用指定的數(shù)據(jù)庫
});
// 建立與數(shù)據(jù)庫的連接。
con.connect(function(err) {
if (err) throw err;
// 如果連接成功
var records = [
['Miley', 13, 85],
['Jobin', 14, 87],
['Amy', 15, 74]
];
con.query("INSERT INTO students (name,rollno,marks) VALUES ?", [records], function (err, result, fields) {
// 如果在執(zhí)行上述查詢時出現(xiàn)任何錯誤,則拋出錯誤
if (err) throw err;
// 如果沒有錯誤,您將得到結(jié)果
console.log(result);
});
});在終端中的Node.js MySQL程序上方運行。
InsertMulIntoExample.js-示例訪問結(jié)果對象的屬性
// 引入mysql模塊
var mysql = require('mysql');
// 創(chuàng)建具有所需詳細(xì)信息的連接變量
var con = mysql.createConnection({
host: "localhost", // 運行mysql的服務(wù)器的IP地址
user: "arjun", // mysql數(shù)據(jù)庫的用戶名
password: "password", // 對應(yīng)的密碼
database: "studentsDB" // 使用指定的數(shù)據(jù)庫
});
// 建立與數(shù)據(jù)庫的連接。
con.connect(function(err) {
if (err) throw err;
// 如果連接成功
var records = [
['Jack', 16, 82],
['Priya', 17, 88],
['Amy', 15, 74]
];
con.query("INSERT INTO students (name,rollno,marks) VALUES ?", [records], function (err, result, fields) {
// 如果在執(zhí)行上述查詢時出現(xiàn)任何錯誤,則拋出錯誤
if (err) throw err;
// 如果沒有錯誤,您將得到結(jié)果
console.log(result);
console.log("Number of rows affected : " + result.affectedRows);
console.log("Number of records affected with warning : " + result.warningCount);
console.log("Message from MySQL Server : " + result.message);
});
});arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node InsertMulIntoExample.js
OkPacket {
fieldCount: 0,
affectedRows: 3,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '&Records: 3 Duplicates: 0 Warnings: 0',
protocol41: true,
changedRows: 0 }
Number of rows affected : 3
Number of records affected with warning : 0
Message from MySQL Server : &Records: 3 Duplicates: 0 Warnings: 0
在本Node.js教程– Node.js MySQL – Node.js MySQL INSERT INTO查詢中,我們學(xué)習(xí)了將一個或多個記錄插入表中并訪問結(jié)果對象的屬性。