Database creation failure, result Undefined - mysql

I am trying to create a simple nodejs code using express and mysql.
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host : 'localhost',
user : 'admin',
password : ''
});
db.connect((err) => {
if(err){
console.log('Error while connecting');
}
console.log('Connected');
});
const app = express();
app.get('/createdb',(req, res) => {
let sql = 'CREATE DATABASE nodemysql';
db.query(sql,(err,result) => {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});
app .listen('4200',() => {
console.log('Server started on port 4200');
});
The response is sent to the browser that says
database created..
but the result it throws is undefined. Also the console that says
Error while creating database is printed
Error I am getting is
[nodemon] restarting due to changes...
[nodemon] restarting due to
changes... [nodemon] starting node index.js
Server started on port 4200
Connected error while creating database
result: undefined
I am not sure on what I am missing out. Please help.

Below code should work fine, try to execute the below code in a .js file. If it works, then we would be sure that nothing wrong in the conf part.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});

I am not an expert, but added the keyword 'function', like below:
app.get('/createdb',(req, res) => {
let sql = 'CREATE DATABASE nodemysql11';
db.query(sql, function(err,result) => {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});

Try this, it will work
app.get('/createdb',(req, res) => {
db.query('CREATE DATABASE nodemysql11', function(err,result) {
if(err){
console.log("error while creating database");
}
console.log('result: '+result);
res.send('database created..');
});
});

Try the below line and then run the .js file.
I assume u have done npm install mysql
mv ./node_modules/node-mysql/node_modules/* ./node_modules/

Related

Why does my middle end node server stop running after I connect to a dabatase

Question: Why is my middle end server not responding after connecting to a database?
Hello, so I have a simple mysql database server running and open in mysql workbench (I ran a test and it is working), and I also have a simple middle end node app to handle and process requests. I can even run a query to make a database in mysql before the api stops responding.
The problem: after I connect to my database, my middle end end points stop working. such as my default page "/" for "hello world". I have very simple and basic node db connection code so I'm not sure why it's failing.
var express = require('express')
var app = express()
var https = require('https')
var mysql = require('mysql')
var cors = require('cors')
app.use(express.json())
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
port: '3306',
database:'mydbtest666'
});
db.connect(function (err) {
if (err) throw err;
console.log("Connected!");
db.destroy();
});
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(5000)
I am using the logger to help log commands, and it will show that the endpoint was called, but no data is being shown on my screen and again the page just loads and loads.
I thought closing/destroying the connection would work, but it is not. Would a try catch change anything??
Here's another attempt with my signup but the middle end still freezes and with this attempt it no longer connects to the database:
app.post("/users/signup", (req, res) => {
const username = req.body.username
const password = req.body.password
db.connect(function (err) {
if (err) throw err;
console.log("Connected!");
try {
db.query("INSERT INTO users (username, password) VALUES (?,?)", [username, password], (err, result) => { });
db.destroy();
} catch (err) {
console.log(err);
}
});
});

How to fetch data from MySQL database with Node

I'm new to react, developing a recipe-app and I got a problem while displaying the data from MySQL database. The connection was created successfully, however, I'm not sure about how to reach the data. When I run node server.js in my terminal, I get "connected", When I visit the localhost:8080/users, I get "This site can't be reached" message and in my terminal:
`events.js:187
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after already enqueuing a Handshake.`
I'm a little stuck here. Anyone knows a solution or direct me a little bit? Thank you so much!
Server.js
const express = require('express');
const app = express();
const PORT = 8080;
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
//creating route for the app
app.get('/users', (req, res) => {
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
res.send(JSON.stringify(rows));
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});
//making server listen to request
app.listen(PORT, () => {
console.log(`Server running at : http://localhost:${PORT}/`);
});
You're trying to reconnect to mysql after the connection has been established.
See my comments on the code below
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => { // This creates the connection
if (err) throw err;
console.log('Connected!');
});
And when you're trying to resolve your GET routes, you're trying to connect again
//creating route for the app
app.get('/users', (req, res) => {
connection.connect(); // reconnect here
Since you're using the default connection method, trying to connect to an already established connection will cause the driver to throw a Handshake error.
If you want to re-use the connection, store it in a variable and then re-use it in other part of your code.
If you want to manage multiple connections instead, I suggest you to look at createPool instead.
Try removing the connection.connect() and connection.end() from app.get

How to fix "err is not defined" error in Nodejs

I'm trying to establish a connection to mysql database in Nodejs but it won't compile as "err is undefined". I'm fairly new to Node.js, but I thought this was the appropriate way to handle errors, even with the mysql package, which is the only difference from my other projects where I did not encounter this issue.
throw err; // Rethrow non-MySQL errors
^
ReferenceError: err is not defined
const express = require('express');
const mysql = require('mysql');
//Create connection
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '123456',
database: 'ca1903'
});
//Connect
db.connect(() => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});
const app = express();
//create DB
app.get('/createdb', () => {
let sql = 'CREATE DATABASE ca1903';
db.query(sql, (err, result) => {
if(err){
console.log(err);
}
console.log(result);
res.send('database created....');
});
});
You were missing err parameter in the db.connect call. It should be in the below way.
// Connect
db.connect((err) => {
if(err){
console.log(err);
}
console.log('MySql Connected');
});

Woking with node.js and mysql

// So I am using mysql with node and express framework and the first time I created a test example everything worked fine. But then I tried to create a second project and now the routing seems to not being read.
And the respond back I get is:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Server started on port 8000
mysql connected...
//I am also supposed to get the result back:
OkPackege{...
...
...
...
}
//But I am not getting it. Any Ideas...? thanks.
The scrips that i have are as follow:
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'LEoking1987'
//database : 'nodesql'
});
db.connect((err) => {
if(err){
throw err;
}
console.log('mysql connected...');
});
const app = express();
// Creates satabase if it does not exist yet.
app.get('/createdb',(req,res) => {
let sql = 'CREATE DATABASE nodesql';
db.query(sql, (err, result) => {
if(err) throw err;
console.log(result);
res.send('Database created...');
});
});
app.listen('8000',()=>{
console.log('Server started on port 8000');
});
add debug: true in your mysql connection params like
mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'LEoking1987'
database: 'nodesql'
debug: true,
})

Simple server handling routes and giving error nodejs mysql

I'm trying to write a simple server using nodejs and have the server ship back different queries and/or custom headers/responses based on the routes. However, in the getUsers() function the error keeps getting hit and printing the 'Error querying' to the console instead of printing the email rows. I know the server is connected fine, because I can return a query when I just use the db and return a query with createConnection only using the second example. Any help spotting the error is greatly appreciated. Thanks.
What I'm trying to get done:
var http = require('http');
var mysql = require('mysql');
var url = require('url');
var util = require('util');
var db = mysql.createConnection({
host : "*********",
user : "*********",
password : "*********",
port : '****',
database : '*********'
});
db.connect(function(err) {
console.log('connected');
if (err)
console.error('Error connecting to db' + err.stack);
});
function getUsers() {
db.query('SELECT * FROM users', function(err, rows, fields) {
if (err)
// changed console.error('Error querying');
console.error(err);
if (rows)
console.log('Rows not null');
for (var i in rows) {
console.log(rows[i].email)
}
});
}
var server = http.createServer(function(req, res) {
console.log(req.url);
if (req.url == '/signup') {
console.log("User signing up");
} else if (req.url == '/signin') {
console.log("User signing in");
} else if (req.url == '/new') {
console.log("User request new game");
getUsers();
}
//res.writeHead(200);
//res.end('Hello Http');
});
server.listen(3000);
// changed and commented out db.end();
What does work with querying the db:
var connection = mysql.createConnection({
host : "********",
user : "********",
password : "********",
port : '****',
database : '********'
});
connection.connect();
var queryString = 'SELECT * FROM users';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log('Users: ', rows[i].email);
}
});
connection.end();
The code has been updated with the changes, and the problem was I was closing the database. After changing the error logs as was suggested in the comments, this was the error received.
{ [Error: Cannot enqueue Query after invoking quit.] code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
I then commented out the
db.end()
and the queries were returned fine.
Thanks for the help.