简体   繁体   English

如何在基于 Node.js 的应用程序和 node-mysql 驱动程序中从 MySQL 数据库中选择多条记录?

[英]How to SELECT multiple records from MySQL DB in an Node.js based application & node-mysql driver?

I am running the below query in mysql db and i want to store the results in an array ?我在 mysql db 中运行以下查询,我想将结果存储在一个数组中? How can I do that in node.js ?我怎么能在 node.js 中做到这一点?

SELECT ProductName FROM products;

The last SELECT statement you have described is almost correct except that it uses structure for the INSERT statement.您描述的最后一条 SELECT 语句几乎是正确的,只是它使用了 INSERT 语句的结构。

Here is 2 correct ways to create and execute SELECT statements, the safe way, to avoid MySQL injections and to secure your database from possible attacks.这里有2 种正确的方法来创建和执行 SELECT 语句,这是一种安全的方法,可以避免 MySQL 注入并保护您的数据库免受可能的攻击。

1. Multiple Records 1. 多条记录

    /**
     * Example of Selecting multiple rows form one MySQL table
     */

    var query = connection.query('SELECT ProductName FROM products', 
    [product_id], function(err, results) { 

         if (error) throw error; output error(s)

         // results[0]['ProductName'];
         // results[1]['ProductName'];
         // ...

    }); 
  1. Using a prepared Statement targeting for specific rows:对特定行使用准备好的 Statement 目标:

     /** * Example of Selecting one record using MySQL Table ID */ var category_id = 5; var query = connection.query('SELECT ProductName FROM products WHERE CategoryId=?', [category_id], function(err, results) { if (error) throw error; output error(s) // results[0]['ProductName']; // results[1]['ProductName']; // ... });
  2. Using mysql.escapeId() method使用 mysql.escapeId() 方法

    var category_id = x; var sql = 'SELECT productName FROM products WHERE category_id = ' + connection.escape(category_id); connection.query(sql, function (error, results, fields) { if (error) throw error; output error(s) // results[0]['ProductName']; // results[1]['ProductName']; // ... });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM