Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I begin MySQL work in Node.js on Windows?

I've begun playing around with Node.js lately, for many reasons but most importantly the ease at which I can write a chat-server utilising HTML5 WebSockets. However, I've been stuck for weeks with MySQL.

I'm currently using this MySQL client module: https://github.com/sidorares/nodejs-mysql-native

I've connected to the database and managed to store data using the following code:

// MySQL database
var db = require("mysql-native").createTCPClient(); // localhost:3306 by default
db.auto_prepare = true;
db.auth(dbName, dbUser, dbPass);
// Update the database
db.execute("UPDATE server_data SET value='" + new Date() + "' WHERE name='lastLoaded'");

How may I go about retrieving data from the database using a SELECT * FROM x WHERE y=z query?

like image 233
User2013 Avatar asked Jan 28 '26 11:01

User2013


1 Answers

Is there any specific reason you chose nodejs-mysql-native over node-mysql which is a really good node module. If there is none, then you should probably try node-mysql. I've tried it and it is great to start off using MySQL with Node. You could do something like:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'your_username',
  password : 'your_password',
});

connection.connect();

connection.query("UPDATE server_data SET value=? WHERE name=?", [new Date(), 'lastLoaded'] function(err, result) {
  if (err) throw err;
  console.log('Result: ', result);
});

connection.end();

The advantage you get by using it this way is that you can prevent SQL injection, which is taken care of internally in node-mysql (by using the connection.escape() method).

like image 182
MT. Avatar answered Jan 31 '26 01:01

MT.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!