How to use existing wamp's MySQL databases in node.js? - mysql

I already have WAMP server installed on my machine. Can I be able to access MySQL databases created on WAMP's MySQL using node-mysql module?
Actually, I tried this code, its running without errors but unable to fetch the database(or tables):
var http = require('http'),
mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "database_name"
});
http.createServer(function (request, response) {
request.on('end', function () {
connection.query('SELECT * FROM table_name', function (error, rows, fields) {
console.log('The first field is: ', rows[0].field);
});
});
}).listen(8001);
console.log("running on localhost:8001");

Try adding request.resume(); before your 'end' event handler.
In node v0.10+, streams start out in a "paused" state that allow you to .read() specific sized chunks or you can use them like the old streams by attaching a 'data' event handler which causes the stream to be continuously read from.
Calling request.resume(); will also switch to the old stream mode, effectively discarding the request data (because there are no 'data' event handlers) so that your 'end' event handler will be called.

Related

How to connect my react native expo project with MySQL? [duplicate]

I'm using React Native. I want to find the data I entered in React Native in the database. For example, in the database of the user name I entered, "select id from table where ('data I entered in react native')". I want to find the table with the user name and pull the user's id.
var name = this.state.username;
"select id from table where (name)"
I want to pull the id of the user name like this.
There is no direct connection between RN and Mysql. Use Node js for this.
Step: 1
npm install express
npm install body-parser
npm install mysql
Step: 2
const connection = mysql.createPool({
host : 'localhost', // Your connection adress (localhost).
user : 'root', // Your database's username.
password : '', // Your database's password.
database : 'my_db' // Your database's name.
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/users', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM users', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/users so you can see the data.');
});
Now, how do we get that data on our React Native App?
That's simple, we use the fetch function.
To do that, instead of using 'localhost:3000', you'll have to directly insert your PC's ip adress. If you use 'localhost', you're acessing your smartphone/emulator's localhost. And that's not what we want. Follow this example:
test(){
fetch('http://yourPCip:3000/users')
.then(response => response.json())
.then(users => console.warn(users))
}
You need to have a backend service/API in order to fetch data from database. try using Node, and write a simple backend since its JavaScript. You can execute sql queries on backend, retrive data from mySQL to your node server and then you can fetch data from the backend server to react-native using fetch method. (both your backend API and the device that running react native application should be running on the same network.)

How can I handle MySQL disconnection on NodeJS?

First of all, I'm a beginner on NodeJS. Well, I'm using a shared hosting to my project and when the database reaches 1 minute of inactivity, NodeJS crashes and disconnects me from MySQL. Since I'm using a shared hosting, I can't edit the idle time on the MySQL config and I'll need to handle it in code.
I'm using module.exports to handle my connection, as shown below. So how can I make an auto-reconnection script to take care of my issue? Thank you.
var mysql = require('mysql');
module.exports =
{
handle: null,
connect: function(call){
this.handle = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'test',
timezone: 'utc',
charset : 'utf8'
});
this.handle.connect(function (err) {
if(err) {
console.log("[MySQL] Connection error: " + err.code);
} else {
console.log("[MySQL] Successfully connected");
}
});
}
};
The node mysql module that you are using also has a connection pooling mechanism.
Check out the docs at https://github.com/mysqljs/mysql#pooling-connections
Connection pools will make you task easier. You can then store the connection pool object and use its getConnection method to obtain a connection. Make sure that you release the connection when you are done with it.
If for some reason you cant use connection pooling then you will have to listen for error event on the connection and handle it accordingly. But I strongly recommend that you use connection pool.

"ER_CON_COUNT_ERROR: Too many connections" Error with pool connections to mysql from node.js

I have about 20 node.js files that use the following configuration to access my db:
var pool = mysql.createPool({
host: databaseHost,
user: databaseUser,
password: databasePassword,
database: databaseName,
multipleStatements: true
});
The functions all use the following pattern:
pool.getConnection(function (err, connection) {
if (err) {
callback(err);
} else {
// Use the connection
var sql = "...sql statement...";
var inserts = [...inserts...];
connection.query(sql, inserts, function (error, results, fields) {
// And done with the connection.
connection.release();
// Handle error after the release.
if (error) {
callback(error);
} else {
callback(null, results);
}
});
}
});
I recently started getting the error:
"ER_CON_COUNT_ERROR: Too many connections"
on calls to any of my functions. I don't really understand the pool concept well enough. If each function is creating a pool, does that create a separate pool each time that function is called?
I understand get connection and release connection. Just don't really get the createPool.
I tried to log the following:
console.log(pool.config.connectionLimit); // passed in max size of the pool
console.log(pool._freeConnections.length); // number of free connections awaiting use
console.log(pool._allConnections.length); // number of connections currently created, including ones in use
console.log(pool._acquiringConnections.length); // number of connections in the process of being acquired
the result was:
10
0
0
0
I can increase the number of connections but would like to have some better understanding of why the problem exists.
If your createPool is called inside functions everytime there has to be a query, then yes, it is grave! Instead, have a different file only for mysql connection. Write a class where you create a pool inside a function, and then in the constructor you could simply return the connection from the pool. That way, if you simply require this file anywhere in your project, and create an object of the class, you could then simply use it to query and release!

Managing database connections in Node.js, best practices?

I'm building an Node application which will query simple and more complex (multiple joins) queries. I'm looking for suggestions on how I should manage the mySQL connections.
I have the following elements:
server.js : Express
router1.js (fictive name) : Express Router middleware
router2.js (fictive name) : Express Router middleware
//this is router1
router.get('/', function (req, res){
connection.connect(function(Err){...});
connection.query('SELECT* FROM table WHERE id = "blah"', function(err,results,fields){
console.log(results);
});
...
connection.end();
})
Should I connect to mysql everytime '/router1/' is requested, like in this example, or it's better to leave one connection open one at start up? As: connection.connect(); outside of: router.get('/',function(req,res){
...
}); ?
I am using mysql2 for this, it is basicly mysql but with promises. If you use mysql you can also do this.
Create a seperate file called connection.js or something.
const mysql = require('mysql2');
const connection = mysql.createPool({
host: "localhost",
user: "",
password: "",
database: ""
// here you can set connection limits and so on
});
module.exports = connection;
Then it is probaly better you create some models and call these from within your controllers, within your router.get('/', (req, res) => {here});
A model would look like this:
const connection = require('../util/connection');
async function getAll() {
const sql = "SELECT * FROM tableName";
const [rows] = await connection.promise().query(sql);
return rows;
}
exports.getAll = getAll;
You can do this with or without promises, it doesn't matter.
Your connection to the pool is automatically released when the query is finished.
Then you should call getAll from your router or app.
I hope this helped, sorry if not.
Connection pooling is how it should be done. Opening a new connection for every request slows down the application and it can sooner or later become a bottleneck, as node does not automatically closes the connections unlike PHP. Thus connection pool ensures that a fixed number of connections are always available and it handles the closing of unnecessary connections as and when required.
This is how I start my express app using Sequelize. For Mongoose, it is more or less simlar except the library API.
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
sequelize.authenticate()
.then(
// On successfull connection, open a port
// and listen to requests. This is where the application
// starts listening to requests.
() => {
const server = http.createServer(app);
server.listen(port);
},
)
.catch(err => {
console.error('Unable to connect to the database:', err);
console.error('Cancelling app server launch');
});
The app is started only after a database connection has been established. This ensures that the server won't be active without any database connection. Connection pool will keep the connections open by default, and use a connection out of the pool for all queries.
If you use createPool mysql will manage opening and closing connections and you will have better performance. It doesn't matter if you use mysql or mysql2 or sequlize. use a separate file for createPool and export it. You can use it everywhere. Don't use classes and just do it functionally for better performance in nodejs.
> npm install mysql
mysql is a great module which makes working with MySQL very easy and it provides all the capabilities you might need.
Once you have mysql installed, all you have to do to connect to your database is
var mysql = require('mysql')
var conn = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database'
})
conn.connect(function(err) {
if (err) throw err
console.log('connected')
})
Now you are ready to begin writing and reading from your database.

Express JS how to include node-mysql object from a different file

I want to include my mysql connection from the same file(in case I have to change sql password or anything I don't want to change in a many files).
Here is my mysql.js file:
module.exports = require('mysql').createConnection(
{
host : 'localhost',
user : 'admin',
password : 'xxxxxxxx',
database : 'database'
}
);
and I want to use like this:
var connection = require(__dirname + '/../../../mysql');
connection.connect();
.
.
.
My problem is it's working only once. When I start the server I can query without any issues, but in the second query I got the following error message in the console:
"Cannot enqueue Handshake after invoking quit."
Does anybody has an idea why not working?
Apparently you no longer need to call connect() after createConnection(), it'll be handled for you on query, if you like.
From the docs:
However, a connection can also be implicitly established by invoking a
query:
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function(err, rows) { // connected!
(unless err is set) });
Depending on how you like to handle your
errors, either method may be appropriate. Any type of connection error
(handshake or network) is considered a fatal error, see the Error
Handling section for more information.
Other than that, you may be calling connect() before calling end() on the same connection, you might want to check for that.
Thanks the help, but I found a solution for my problem. I just created the variables on my mysql.js file then I exported them like this:
var host = 'localhost';
module.exports.localhost = localhost;
After I can use it on another js file:
var connection = require(__dirname + '/../../../mysql');
connection.localhost;
I found it on this article:
http://openmymind.net/2012/2/3/Node-Require-and-Exports/