I\'ve just started getting into Node.js. I come from a PHP background, so I\'m fairly used to using MySQL for all my database needs.
How can I use MySQL with Node.js
Imo, you should try MySQL Connector/Node.js which is the official Node.js driver for MySQL. See ref-1 and ref-2 for detailed explanation. I have tried mysqljs/mysql which is available here, but I don't find detailed documentation on classes, methods, properties of this library.
So I switched to the standard MySQL Connector/Node.js
with X DevAPI
, since it is an asynchronous Promise-based client library and provides good documentation.
Take a look at the following code snippet :
const mysqlx = require('@mysql/xdevapi');
const rows = [];
mysqlx.getSession('mysqlx://localhost:33060')
.then(session => {
const table = session.getSchema('testSchema').getTable('testTable');
// The criteria is defined through the expression.
return table.update().where('name = "bar"').set('age', 50)
.execute()
.then(() => {
return table.select().orderBy('name ASC')
.execute(row => rows.push(row));
});
})
.then(() => {
console.log(rows);
});
KnexJs can be used as an SQL query builder in both Node.JS and the browser. I find it easy to use. Let try it - Knex.js
$ npm install knex --save
# Then add one of the following (adding a --save) flag:
$ npm install pg
$ npm install sqlite3
$ npm install mysql
$ npm install mysql2
$ npm install mariasql
$ npm install strong-oracle
$ npm install oracle
$ npm install mssql
var knex = require('knex')({
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test'
}
});
You can use it like this
knex.select('*').from('users')
or
knex('users').where({
first_name: 'Test',
last_name: 'User'
}).select('id')
Since this is an old thread just adding an update:
If you run just npm install mysql
, you need to be in the same directory that your run your server. I would advise to do it as in one of the following examples:
npm install -g mysql
1- Add it to your package.json
in the dependencies:
"dependencies": {
"mysql": "~2.3.2",
...
2- run npm install
Note that for connections to happen you will also need to be running the mysql server (which is node independent)
There are a bunch of tutorials out there that explain this, and it is a bit dependent on operative system. Just go to google and search for how to install mysql server [Ubuntu|MacOSX|Windows]
. But in a sentence: you have to go to http://www.mysql.com/downloads/ and install it.