Jack M.
Jack M.

Reputation: 3804

NodeJS get values from SQL query

I have https://www.npmjs.org/package/mysql module.

They show examples how to use it when multiple rows are expected, but I couldn't find one example showing how to fetch a single result into a variable.

SELECT name FROM users WHERE id=1 LIMIT 1

how do I fetch this into sqlValues variable ?

Upvotes: 1

Views: 10828

Answers (3)

user10124251
user10124251

Reputation:

you can implement this code like this … (more simple)

var queryString = 'SELECT name FROM users WHERE id=1 LIMIT 1';

connection.query(queryString, function(err, rows) {
    if (err) throw err
     res.send(rows)
     console.log(rows)//this 
});

connection.end();

Upvotes: 0

Navoneel Talukdar
Navoneel Talukdar

Reputation: 4598

You can see the code below which connects to sql and fetches data.

var mysql = require('mysql');

var connection = mysql.createConnection(
    {
      host     : 'localhost',
      user     : 'your-username',
      password : 'your-password',
      database : 'wordpress',
    }
);

connection.connect();

var queryString = 'SELECT name FROM users WHERE id=1 LIMIT 1';

connection.query(queryString, function(err, rows, fields) {
    if (err) throw err;

    for (var i in rows) {
        console.log('Post Titles: ', rows[i].yourcolumnname);
    }
});

connection.end();

Upvotes: 0

Sinkingpoint
Sinkingpoint

Reputation: 7624

In the callback function of the .query method, the second parameter contains an array containing the rows returned from your query. No matter how many are returned, these can be indexed just as an array.

Thus, in the callback function to get the single expected result, you can use rows[0].

In your specific instance, to assign the returned name field to the sqlValues variable, you can use a simple assignment: sqlValues = rows[0].name

Upvotes: 3

Related Questions