在本教程中,您将学习如何从node.js应用程序将一行或多行插入到表中。
要在表中插入新行,请按照下列步骤操作:
- 连接到MySQL数据库,参阅:http://www.yiibai.com/mysql/nodejs-connect.html
- 通过在
connection
对象上调用query()
方法来执行INSERT语句。 - 关闭数据库连接。
请注意,我们将重用包含MySQL数据库信息的config.js模块。
如果您没有从上一个教程开始,那么可以参考这里的config.js
模块:
let config = {
host : 'localhost',
user : 'root',
password: '123456',
database: 'todoapp'
};
module.exports = config;
将一行数据插入表中
以下insert.js
程序将向todos
表中插入一个新行:
let mysql = require('mysql');
let config = require('./config.js');
let connection = mysql.createConnection(config);
// insert statment
let sql = `INSERT INTO todos(title,completed)
VALUES('Learn how to insert a new row',true)`;
// execute the insert statment
connection.query(sql);
connection.end();
下面,我们来执行insert.js
程序。
F:\worksp\mysql\nodejs\nodejs-connect>node insert.js
openssl config failed: error:02001003:system library:fopen:No such process
并检查todos
表中的数据:
mysql> select * from todos;
+----+-------------------------------+-----------+
| id | title | completed |
+----+-------------------------------+-----------+
| 1 | Learn how to insert a new row | 1 |
+----+-------------------------------+-----------+
1 row in set (0.00 sec)
在上面查询结果中,您可以看到,程序向todos
表中插入一个新行。
插入一行并返回插入的ID
以下insert-lastid.js
程序将一个新行插入到todos
表中,并返回插入的id
。
let mysql = require('mysql');
let config = require('./config.js');
let connection = mysql.createConnection(config);
let stmt = `INSERT INTO todos(title,completed)
VALUES(?,?)`;
let todo = ['Insert a new row with placeholders', false];
// execute the insert statment
connection.query(stmt, todo, (err, results, fields) => {
if (err) {
return console.error(err.message);
}
// get inserted id
console.log('Todo Id:' + results.insertId);
});
connection.end();
要将数据传递给SQL语句,请使用问号(?
)作为占位符。
在这个例子中,我们分别使用两个问号(?
,?
)作为title
和completed
字段。
执行查询后,可以从results
对象的insertId
属性中获取插入的id
,如下所示 -
F:\worksp\mysql\nodejs\nodejs-connect>node insert-lastid.js
openssl config failed: error:02001003:system library:fopen:No such process
Todo Id:2
一次插入多行
以下insert-more.js
程序一次将多行插入到todos
表中:
let mysql = require('mysql');
let config = require('./config.js');
let connection = mysql.createConnection(config);
// insert statment
let stmt = `INSERT INTO todos(title,completed) VALUES ? `;
let todos = [
['Insert multiple rows at a time', false],
['现在学习一次插入多行记录(by www.yiibai.com)', true],
['It should work perfectly', true]
];
// execute the insert statment
connection.query(stmt, [todos], (err, results, fields) => {
if (err) {
return console.error(err.message);
}
// get inserted rows
console.log('Row inserted:' + results.affectedRows);
});
// close the database connection
connection.end();
请注意,我们在INSERT
语句中只使用一个问号(?
),多行数据是数组数组。
您可以访问通过results
对象的affectedRows
属性插入的行数。
F:\worksp\mysql\nodejs\nodejs-connect>node insert-more.js
openssl config failed: error:02001003:system library:fopen:No such process
Row inserted:3
如结果所示,插入了三行,这是像我们预期的那样。
在本教程中,您已经学习了如何从node.js程序将一行或多行插入到表中。