How to create MySQL database connection in Coffeescript - mysql

How to connect MySQL database in CoffeeScript. How to run this.I created MySQL connection using node.js and display record in terminal but how to display this on browser.I am using ECO templating for displaying on browser. I need database connection using coffeescript
file - db_test.js
var mysql = require("mysql");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test"
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.query('SELECT * FROM users',function(err,rows){
if(err) throw err;
for (var i = 0; i < rows.length; i++) {
console.log(rows[i].username);
};
});
con.end(function(err) {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});

CoffeeScript is just javascriptâ„¢
Any javascript library should be usable in CoffeeScript because at the end of the day, the CS is just getting converted to JS and running in your usual runtime. This means you would connect just the same (same libraries, methods, etc), just different syntax.
The only advantage of CoffeeScript is that it's nicer to write than JS, if you don't know CoffeeScript, there's little reason to use it at all, and in fact you're just making your life harder by adding a compilation step to your production.
If you must absolutely use CS, there are tools to cross-compile between the two (like js2.coffee), but I strongly suggest you learn CoffeeScript and write it on your own so you get its advantages and not just its burdens. There are plenty of resources online.

Related

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.

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.

Connect Node with mysqli module?

I want to connect Node JavaScript with Mysqli. I have downloaded the mysqli module using following command.
npm install mysqli
And Then Create JavaScript file with following code.
var Mysqli = require('mysqli');
// incoming json
let conn = new Mysqli ( {
host: "localhost",
user: "root",
password: "",
database: "ll"
} );
conn.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM post", function (err, result) {
if (err) throw err;
console.log(result);
});
});
But not able to connect to database.
I have used following Packages.
https://www.npmjs.com/package/mysqli
You have a typo here:
conn.query
Unless, of course, you wrote the code here again. I am sure you would have figured that out by now, but still... After all, this is the first thing that comes up when someone searches for mysqli nodejs.
If connecting to mysql db is the goal, then I suggest you to use mysql module.
install mysql module by running npm install mysql
below is the sample code for how to use the mysql module
const mysql = require('mysql');
const conn = mysql.createConnection(
{
host:'your_host', //localhost in your case
user:'db_user', // root in your case
password: 'password', //blank string in your case
database:'your_db_name' //'ll' in your case
});
//executing the queries
conn.query('SELECT * from post',function(err,result){ //result of the query is stored in 'result' and the error, if any, are stored in err
if(err)
{
console.log(err);
}
else
{
console.log(result);
}
});
click this link for further information
The module which you're using seems to be a newer one and which is not stable.
Consider using mysql module which has been accepted by many developers, it has a great documentation and an active github community + google mailing list and IRC channel.

Node.Js - no output from mysql connection

Sorry in advance - using nodejs for the first time..
I have installed nodejs and npm manager on linux machine. Through the npm I installed mysql module and now I try to test the mysql connection using the simple code. The problem is - no output is printed to the console, when the mysql related code is run!
source:
var mysql = require("mysql");
console.log('1');
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "xxx",
password: "xxxx",
database: "xxx",
port: 3306
});
console.log('2');
connection.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
console.log('3');
connection.end(function(err) {
console.log('Connection closed');
});
console.log('4');
process.exit();
The output is 1234:
Here are installed modules:
So my question is - why are there no messages coming from mysql connection? I tried to enter incorrect connection details on purpose - no messages were produced.
I also tried running node as sudo and also tried running nodejs index.js instead of node index.js. Oh, and I also tried to install and use nodejs-mysql module instead of mysql. Nothing seems to be working.
You're writing asynchronous code, so you need to wait for those operations to complete before you force kill the process.
What you're essentially saying is "Do this, do this, do this, and get back to me later. Also shut everything down right now."
Remove the process.exit call or move it inside a callback function so it's triggered at the right time:
var connection = mysql.createConnection({
...
});
console.log('2');
connection.connect(function(err){
if(err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
console.log('3');
connection.end(function(err) {
console.log('Connection closed');
console.log('4');
process.exit();
});
});
This aggressive nesting and re-nesting is why things like promises exist. Bluebird is a great library for implementing and using these and is used by database wrappers like Sequelize to keep your code organized.

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

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.