today I tried node.js mysql snippet from w3schools:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "roots", // WRONG USER
password: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
I wanted to learn how to handle mysql errors, because my app require mysql. But after I started app.js file this error showed up:
Why can't I throw an error?
I wanted to learn how to handle mysql errors, because my app require
mysql.
MySQLJS Error handling
To catch the errors you throw, try with the following snippet :
con.on('error', function(err) {
console.log("[mysql error]",err);
});
change you're database conn like this
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'secret'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
Related
I have the following code. When i execute it, i get
Database connected successfully! 1 record inserted. But it saves no data in MySql database.
Im pretty sure my code is correct, but do someone has any tip or advice?
var mysql = require('mysql');
var dbconn = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "assessment"
});
dbconn.connect(function(err) {
if (err) throw err;
console.log("Database connected successfully!");
var sqlquery = "INSERT INTO users (username,password) VALUES ('john', 'jmpleom')";
dbconn.query(sqlquery, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record inserted");
});
});
Have you tried committing the data to the database? As a failsafe from unfinished queries, databases will rollback any records to their original state if the data is not committed to the database.
After your insert query, try it out. Based on your code it might look something like this:
dbconn.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
To save or commit data you have to end the connection like this:
dbconn.connect(function(err) {
if (err) throw err;
console.log("Database connected successfully!");
var sqlquery = "INSERT INTO users (username,password) VALUES('john','jmpleom')";
dbconn.query(sqlquery, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record inserted");
dbconn.end(); //like this
});
I have a web server run by node.js
It uses Express, Socket.io, and MySQL
I use socket.io to transmit data from client to server, and also to call queries.
After implementing SQL connexion and queries, the server started to stop after exactly 60 seconds running it.
SQL part in the index.js file:
// SQL
var mysql = require('mysql');
var con = mysql.createConnection({
host: "...",
user: "...",
password: "...",
database: "..."
});
//Socket.io
var io = require('socket.io') (serv, {});
io.sockets.on('connection', function(socket) {
// Select
socket.on("recherche", function(data) {
if (err) throw err;
con.query("SELECT * FROM ..", function (err, result, fields) {
if (err) throw err;
socket.emit("...", {data: result});
});
});
// Insert into
socket.on("...", function(data) {
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO ... VALUES (...)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
});
Everything is working just fine for 60 second after start the server.
Then, I have this error message in the nodejs console:
C:\Users\...>node index.js
events.js:187
throw er; // Unhandled 'error' event
^
...
Error: Connection lost: The server closed the connection.
...
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
Thank you in advance to read my question :D
connection = mysql.createConnection(db_config); // Recreate the connection, since
connection.connect(function(err) {
if(err) {
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000);
}
});
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect();
} else {
throw err;
}
});
I have a code bellow and it is running fine (getting data from database) but when I run it from a terminal (e.g. node db.js) - it gives data back but never closes (can not type next command in terminal.
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '...',
user: '...',
password: "...,
port : ..., //port mysql
database: '...'
});
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM table", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
What should be added to the end of .js ?
You can end connections with connection.end();
You must add it after the query because the query must be completed first. Here is your modified code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '...',
user: '...',
password: "...,
port : ..., //port mysql
database: '...'
});
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM table", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
connection.end();
});
Closing the connection is done using end() which makes sure all
remaining queries are executed before sending a quit packet to the
mysql server.
https://github.com/mysqljs/mysql#introduction
because all the queries must complete before ending a connection put the following line outside the callback:
connection.end();
You can end the process by calling the
process.exit(); method.
You need to tell MySQL.js to close the connection, once you're done with the query. For example:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '...',
user: '...',
password: "...,
port : ..., //port mysql
database: '...'
});
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM table", function (err, result, fields) {
if (err) throw err;
console.log(result);
connection.end(function (err) { if (err) throw err; } });
});
});
For more info, see MySQL.js docs: https://github.com/mysqljs/mysql#terminating-connections
I do some mistake with connecting mysql in express which i couldn't figure out.
The basic connection code below works well.
var connection = mysql.createConnection({
host : 'localhost',
user:'root',
password:'',
database :'testdb'
});
connection.connect();
connection.query('SELECT * from test2table', function (err, data) {
if (err) throw err
console.log('The solution is: '+JSON.stringify(data)); -->could obtain data
});
But when it comes to use inside a get/post method , i donot get a response. Like code below:
var connection = mysql.createConnection({
host : 'localhost',
user:'root',
password:'',
database :'testdb'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
app.get('/api/records',function(req,res){
connection.query('SELECT * from test2table', function (err, data) {
console.log(data);--> get blank response
});
});
Please let me know if i missed anything inbetween which affects. Thankyou.
Can you try with app.locals?
var connection = mysql.createConnection({
host : 'localhost',
user:'root',
password:'',
database :'testdb'
});
connection.connect(function(err){
if(err) throw err;
console.log("connected");
});
app.locals.connection = connection;
app.get('/api/records',function(req,res){
app.locals.connection.query('SELECT * from test2table', function (err, data) {
console.log(data);--> get blank response
});
});
See more details here: http://expressjs.com/en/api.html#app.locals
Hi I am currently trying to output mysql data to a browser window instead of the console, and I have not a clue on how to do this in Node, which I am quite new to.
Here is the mysql.js file:
'
var mysql = require ("mysql");
var connection = mysql.createConnection({
host:"localhost",
user: "root",
});
connection.connect(function (err) {console.log( "Successfully Connected.");
if (err) throw err;
});
var query = connection.query("SELECT * FROM myTable", function (err, result, fields){
if (err) throw err;
console.log('result:', result);
});
connection.end();'
You need to create a server which you can connect to and receive data from with a browser. The most convenient and by far the simplest way to do this is HTTP. You can read about HTTP servers in node.js here. The fist code snippet on that page demonstrates a HTTP server with one handler function, which is all you need to achieve your goal.
An (untested) example for convenience:
// Dependencies
var mysql = require("mysql"),
http = require("http");
// This holds our query results
var results;
// Connect to database
var connection = mysql.createConnection({
host: "localhost",
user: "root"
});
connection.connect(function(err) {
if (err) throw err;
console.log("Connected to database");
});
connection.query("SELECT * FROM myTable", function(err, rows, fields) {
if (err) throw err;
results = rows;
connection.end(); // Disconnect from database
});
// Function to handle browser's requests
function requestHandler(req, res) {
res.end(JSON.stringify(results)); // Respond to request with a string
}
// Create a server
var server = http.createServer(requestHandler);
// That magic number 8080 over here is the port our server listens to.
// You can access this webpage by visiting address http://localhost:8080
server.listen(8080, function() {
console.log("Server online");
});