Node.js MySQL INSERT INTO查询用于将一个或多个记录插入MySQL表。
Node.js MySQL插入
Node.js MySQL示例,将记录插入表中
Node.js MySQL示例,将多条记录插入表中
访问结果对象的属性
Node.js MySQL示例,将记录插入表中
InsertIntoExample.js
//引入mysql模块
var mysql = require('mysql');
// 创建具有所需详细信息的连接变量
var con = mysql.createConnection({
host: "localhost", // 运行mysql的服务器的IP地址
user: "arjun", // mysql数据库的用户名
password: "password", // 对应的密码
database: "studentsDB" // 使用指定的数据库
});
// 建立与数据库的连接。
con.connect(function(err) {
if (err) throw err;
// 如果连接成功
con.query("INSERT INTO students (name,rollno,marks) values ('Anisha',12,95)", function (err, result, fields) {
// 如果在执行上述查询时出现任何错误,则抛出错误
if (err) throw err;
// 如果没有错误,您将得到结果
console.log(result);
});
});
在终端中的Node.js MySQL程序上方运行。
InsertMulIntoExample.js-将多个记录插入表的示例
//引入mysql模块
var mysql = require('mysql');
// 创建具有所需详细信息的连接变量
var con = mysql.createConnection({
host: "localhost", // 运行mysql的服务器的IP地址
user: "arjun", // mysql数据库的用户名
password: "password", // 对应的密码
database: "studentsDB" // 使用指定的数据库
});
// 建立与数据库的连接。
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) {
// 如果在执行上述查询时出现任何错误,则抛出错误
if (err) throw err;
// 如果没有错误,您将得到结果
console.log(result);
});
});
在终端中的Node.js MySQL程序上方运行。
InsertMulIntoExample.js-示例访问结果对象的属性
// 引入mysql模块
var mysql = require('mysql');
// 创建具有所需详细信息的连接变量
var con = mysql.createConnection({
host: "localhost", // 运行mysql的服务器的IP地址
user: "arjun", // mysql数据库的用户名
password: "password", // 对应的密码
database: "studentsDB" // 使用指定的数据库
});
// 建立与数据库的连接。
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) {
// 如果在执行上述查询时出现任何错误,则抛出错误
if (err) throw err;
// 如果没有错误,您将得到结果
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查询中,我们学习了将一个或多个记录插入表中并访问结果对象的属性。