使用 Node 查询表中的数据
在本文中,我们将了解如何基于不同的表字段和列从数据库选择或查询数据。
在继续之前,请检查已执行以下步骤:
mkdir mysql-test
cd mysql-test
npm init -y
npm install mysql
以上步骤用于在项目文件夹中安装 Node - mysql 依赖项。
使用 Node 从表中选择数据
创建名为 app.js 的新文件
将以下代码段复制并粘贴到此文件中。
现在,运行以下命令以检查上述程序的输出。
>> node app.js
示例
// Checking the MySQL dependency – if exists
var mysql = require('mysql');
// Creating connection with the mysql database
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err)
console.log("Unable to connect to DB ", err);
con.query("SELECT * FROM students", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});输出
It will return all the records present in the students table:
[ RowDataPacket { id: 1, name: 'John', address: 'Delhi'},
RowDataPacket { id: 2, name: 'Pete', address: 'Mumbai'},
RowDataPacket { id: 3, name: 'Amy', address: 'Hyderabad'},
RowDataPacket { id: 4, name: 'Hannah', address: 'Mumbai'},
RowDataPacket { id: 5, name: 'Mike', address: 'Delhi'}]使用 Node 查询表中的数据
以下代码段举例说明了我们如何使用 SQL 查询来查询数据并在 Node 中选择数据。
示例
// Checking the MySQL dependency – if exists
var mysql = require('mysql');
// Creating connection with the mysql database
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err)
console.log("Unable to connect to DB ", err);
con.query("SELECT * FROM student where address='Delhi'; ", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});输出
它将根据我们的筛选条件返回结果:
[ RowDataPacket { id: 1, name: 'John', address: 'Delhi'},
RowDataPacket { id: 5, name: 'Mike', address: 'Delhi'}]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP