mysql connection not working? - What am i doing wrong? - mysql

I'm trying to connect to a mysql database. That's it... But i can't manage to make it work...
My code is separated in two files WebServer.js where i just listen for request and db.js where i put a class that manage the database.
So here's my code:
db.js:
const mysql = require('mysql');
module.exports = class db {
constructor(host, user, pass, database){
this.db = mysql.createConnection({
host: host,
user: user,
password: pass,
database: database,
});
this.db.connect(function(err) {
if (err) {
throw err;
}
console.log('DB connection successful as id ' + connection.threadId);
});
}
}
WebServer.js (Only the part that touch the db.js):
const db = require("./db");
////
var mdb = new db('localhost', "GarageHelper", "GarageHelper", "Garage Helper");
I'm getting this error:
/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/protocol/Parser.js:437
throw err; // Rethrow non-MySQL errors
^
ReferenceError: connection is not defined
at Handshake.<anonymous> (/media/DisqueExterne/Codes source/iut/GarageHelper/db.js:16:61)
at Handshake.<anonymous> (/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/Connection.js:526:10)
at Handshake._callback (/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/Connection.js:488:16)
at Handshake.Sequence.end (/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
at Handshake.Sequence.OkPacket (/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/protocol/sequences/Sequence.js:92:8)
at Protocol._parsePacket (/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/protocol/Protocol.js:291:23)
at Parser._parsePacket (/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/protocol/Parser.js:433:10)
at Parser.write (/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/protocol/Parser.js:43:10)
at Protocol.write (/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/protocol/Protocol.js:38:16)
at Socket.<anonymous> (/media/DisqueExterne/Codes source/iut/GarageHelper/node_modules/mysql/lib/Connection.js:88:28)
I have NodeJS v12.19.0 (try on v17.3.0 on an other machine (i changed the host to the ip of the db) but same error)
mysql was installed using npm install mysql with npm v8.3.0
I searched for hours the issue but i don't see how i'm doing somthing wrong with this little of code...
The error seems to come from the mysql lib but how the lib could be broken?
Maybe i missing something.
Anyway, i'm desperate... Thanks for any help...

Related

"Error: ER_NO_SUCH_TABLE: Table 'managementapp.medicament' doesn't exist"

I'm working in simple CRUD application using react, node and express.. so i connected to my mysql data base "managementapp" and i tried to insert information in my db, but im always getting the error "table doesn't exist while i tested locally and it works properly in mysql wrokbensh and im so sure that im spelling the name of my table correctly. so this the code of App.js for react :
function App() {
const [name,setName]=useState("");
const [description,setDescription]=useState("");
const [number,setNumbre]=useState(0);
const addMedicament = () => {
console.log(name);
Axios.post("http://localhost:3001/create",
{name:name,
description:description,
number:number,
}).then(()=>{
console.log("succes");
});
};
and this my index.js for backend part
const db=mysql.createConnection({
user:"root",
host:"localhost",
password:"",
database:"managementapp",
});
app.post("/create", (req, res) => {
console.log(req.body);
const name=req.body.name;
const description=req.body.description;
const number=req.body.number;
db.query(
"insert into medicament (name,description,number) VALUES (?,?,?);",
[name,description,number],
(err,result) =>{
if (err)
{ console.log(err);
}
else { res.send("Values inserted !! ");
}
}
);
});
so im always getting this error
{ name: 'erty', description: 'rtyuk', number: '86' }
Error: ER_NO_SUCH_TABLE: Table 'managementapp.medicament' doesn't exist
at Query.Sequence._packetToError (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\sequences\Query.js:79:18)
at Protocol._parsePacket (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\Chahine\Management\server\node_modules\mysql\lib\Connection.js:88:28)
at Socket.<anonymous> (C:\Users\Chahine\Management\server\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:290:12)
--------------------
at Protocol._enqueue (C:\Users\Chahine\Management\server\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (C:\Users\Chahine\Management\server\node_modules\mysql\lib\Connection.js:198:25)
at C:\Users\Chahine\Management\server\index.js:25:8
at Layer.handle [as handle_request] (C:\Users\Chahine\Management\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Chahine\Management\server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Chahine\Management\server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Chahine\Management\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Chahine\Management\server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\Chahine\Management\server\node_modules\express\lib\router\index.js:341:12)
at next (C:\Users\Chahine\Management\server\node_modules\express\lib\router\index.js:275:10)
{
code: 'ER_NO_SUCH_TABLE',
errno: 1146,
sqlMessage: "Table 'managementapp.medicament' doesn't exist",
sqlState: '42S02',
index: 0,
sql: "insert into medicament (name,description,number) VALUES ('erty','rtyuk','86');"
}
i was searching since last night and i found that the problem was with my mysql installation .. so i uninstalled it and reinstall it then i changed the port from 3306 to another cause it was already in use .. then i had the error about
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol
requested by server; consider upgrading MySQL client
so i just get into mysql and run a query saying root is fine using old mysql_native_password method for authentication:
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'YourRootPassword';
and everything went right. thanks to Aidin's explanation.

Unknown column "something" in `Field list`, What's wrong?

I'm writing a server at port 3000 and its job is to get the data from "Signup.ejs" input's values and then inserting them into the database.
All is fine but there's a problem, it says to me that TechnoBoy is an unknown column in Field list
I tried inserting "" or even `` around ${} but it didn't work well since a new error has appeared.
This is my Connection.js file that I use it to create a connection and then export it to connect it in my app's files:
let mysql = require("mysql");
let connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "something",
database: "test"
});
module.exports = connection;
And this is my Server.js that I use it to create a server and connect to the database insert the data into it:
let connection = require("./Connection.js");
let bodyParser = require("body-parser");
let express = require("express");
let app = express();
let urlencodedParser = bodyParser.urlencoded({ extended: false });
app.listen(3000, function() {
console.log("The server at port 3000 is open!");
});
app.set("view engine", "ejs");
app.get("/Signup", (req, res) => {
res.render("Register");
});
connection.connect();
app.post("/Signup", urlencodedParser, function(req, res) {
console.log(req.body);
res.render("Register");
connection.query(
`insert into users (Username, User_Password) values (${
req.body.Username
}, ${req.body.Password})`
);
});
Error I receive when I insert some data into input fields:
Error: ER_BAD_FIELD_ERROR: Unknown column 'TechnoBoy' in 'field list'
at Query.Sequence._packetToError (C:\Users\ha\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Query.ErrorPacket (C:\Users\ha\node_modules\mysql\lib\protocol\sequences\Query.js:77:18)
at Protocol._parsePacket (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (C:\Users\ha\node_modules\mysql\lib\protocol\Parser.js:76:12)
at Protocol.write (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket.<anonymous> (C:\Users\ha\node_modules\mysql\lib\Connection.js:91:28)
at Socket.<anonymous> (C:\Users\ha\node_modules\mysql\lib\Connection.js:502:10)
at Socket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
--------------------
at Protocol._enqueue (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Connection.query (C:\Users\ha\node_modules\mysql\lib\Connection.js:200:25)
at C:\Users\ha\OneDrive\Images\Documents\Projects\UI-Server\Server.js:17:14
at Layer.handle [as handle_request] (C:\Users\ha\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\ha\node_modules\express\lib\router\route.js:137:13)
at C:\Users\ha\node_modules\body-parser\lib\read.js:130:5
at invokeCallback (C:\Users\ha\node_modules\raw-body\index.js:224:16)
at done (C:\Users\ha\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\Users\ha\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (events.js:182:13)
Emitted 'error' event at:
at Connection._handleProtocolError (C:\Users\ha\node_modules\mysql\lib\Connection.js:425:8)
at Protocol.emit (events.js:182:13)
at Protocol._delegateError (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:390:10)
at Query.<anonymous> (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:153:12)
at Query.emit (events.js:182:13)
at Query.Sequence.end (C:\Users\ha\node_modules\mysql\lib\protocol\sequences\Sequence.js:78:12)
at Query.ErrorPacket (C:\Users\ha\node_modules\mysql\lib\protocol\sequences\Query.js:90:8)
at Protocol._parsePacket (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (C:\Users\ha\node_modules\mysql\lib\protocol\Parser.js:76:12)
at Protocol.write (C:\Users\ha\node_modules\mysql\lib\protocol\Protocol.js:38:16)
The query I used(which is in connection.query btw):
insert into users (Username, User_Password) values (${
req.body.Username
}, ${req.body.Password})
Excuse me if this is a stupid question or something, I'm very new to backend and this one is my first try on it.
I'm an idiot. I configured Password field to be int so it can't enter strings but I passed it a string, that's why when I was passing it, it was saying wrong syntax and stuff.
Oh and also, I forgot to wrap the username with "" although I still don't know how it is a problem when the property is a string itself.
Problem got solved, it can be closed now.

Connection to MySql with Node JS and Sequelize

When I try to connect from node to my MySql database that runs on the same machine (debian), with a specific user and password I get an "Access denied" error.
If I try the same, with the same user and set no password in the database and node, everything works.
Also connection from the terminal WITH password works fine.
I already tried to delete user and database and recreated them. But nothing works.
This is my node code:
var http = require('http');
var fs = require('fs');
var Sequelize = require('sequelize')
var sequelize = new Sequelize('mysql://user:password#localhost:3306/databasename');
http.createServer(function (req, res) {
console.dir(req.url);
sequelize.query("SELECT ##version;").spread(function(results, metadata) {
console.log(results);
})
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('ok');
}).listen(8080);
What I get on the console is this:
Possibly unhandled Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'user'#'localhost' (using password: YES)
at Handshake.Sequence._packetToError (/var/www/html/node/node_modules/mysql/lib/protocol/sequences/Sequence.js:30:14)
at Handshake.ErrorPacket (/var/www/html/node/node_modules/mysql/lib/protocol/sequences/Handshake.js:67:18)
at Protocol._parsePacket (/var/www/html/node/node_modules/mysql/lib/protocol/Protocol.js:197:24)
at Parser.write (/var/www/html/node/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/var/www/html/node/node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.ondata (_stream_readable.js:555:20)
at emitOne (events.js:101:20)
at Socket.emit (events.js:191:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
--------------------
at Protocol._enqueue (/var/www/html/node/node_modules/mysql/lib/protocol/Protocol.js:110:26)
at Protocol.handshake (/var/www/html/node/node_modules/mysql/lib/protocol/Protocol.js:42:41)
at Connection.connect (/var/www/html/node/node_modules/mysql/lib/Connection.js:81:18)
at ConnectorManager.connect (/var/www/html/node/node_modules/sequelize/lib/dialects/mysql/connector-manager.js:314:16)
at Object.create (/var/www/html/node/node_modules/sequelize/lib/dialects/mysql/connector-manager.js:138:19)
at createResource (/var/www/html/node/node_modules/generic-pool/lib/generic-pool.js:258:13)
at dispense (/var/www/html/node/node_modules/generic-pool/lib/generic-pool.js:250:9)
at Object.me.acquire (/var/www/html/node/node_modules/generic-pool/lib/generic-pool.js:316:5)
at CustomEventEmitter.fct (/var/www/html/node/node_modules/sequelize/lib/dialects/mysql/connector-manager.js:248:19)
at CustomEventEmitter.<anonymous> (/var/www/html/node/node_modules/sequelize/lib/emitters/custom-event-emitter.js:24:18)
Any clues?
Ok, the problem was, package.json did not contain the dependency (mysql or sequelize). I still don't know, why I could connect to the database without password though.
But now it works.

node-webkit MySQL connection Error - ER_HANDSHAKE_ERROR: Bad handshake

I am using Node-Webkit for creating desktop application using NodeJS.
In this i need to get data from MySQL database. For this am using node-mysql module and the following code is used to connect MySQL server using node-mysql.
var mysql_con = require('mysql');
var connection = mysql_con.createConnection({
host : input.host,
user : input.username,
password : input.password,
database : input.database
});
connection.connect(function(err) {
if (err) {
console.log('Error : '+err.stack);
}
console.log('Success');
});
if i run in the command line of my Windows machine, connection has been established and Success has been printed in console. But if i pack and run the code in the node-webkit's nw.exe its giving the following error in web console
Error : Error: ER_HANDSHAKE_ERROR: Bad handshake
at Handshake.Sequence._packetToError (C:\DOCUME~1\admin\LOCALS~1\Temp\nw4480_11607\node_modules\mysql\lib\protocol\sequences\Sequence.js:48:14)
at Handshake.ErrorPacket (C:\DOCUME~1\admin\LOCALS~1\Temp\nw4480_11607\node_modules\mysql\lib\protocol\sequences\Handshake.js:101:18)
at Protocol._parsePacket (C:\DOCUME~1\admin\LOCALS~1\Temp\nw4480_11607\node_modules\mysql\lib\protocol\Protocol.js:270:23)
at Parser.write (C:\DOCUME~1\admin\LOCALS~1\Temp\nw4480_11607\node_modules\mysql\lib\protocol\Parser.js:77:12)
at Protocol.write (C:\DOCUME~1\admin\LOCALS~1\Temp\nw4480_11607\node_modules\mysql\lib\protocol\Protocol.js:39:16)
at Socket.<anonymous> (C:\DOCUME~1\admin\LOCALS~1\Temp\nw4480_11607\node_modules\mysql\lib\Connection.js:82:28)
at Socket.EventEmitter.emit (events.js:104:17)
at readableAddChunk (_stream_readable.js:156:16)
at Socket.Readable.push (_stream_readable.js:123:10)
at TCP.onread (net.js:520:20)
--------------------
at Protocol._enqueue (C:\DOCUME~1\admin\LOCALS~1\Temp\nw4480_11607\node_modules\mysql\lib\protocol\Protocol.js:135:48)
at Protocol.handshake (C:\DOCUME~1\admin\LOCALS~1\Temp\nw4480_11607\node_modules\mysql\lib\protocol\Protocol.js:52:41)
at Connection.connect (C:\DOCUME~1\admin\LOCALS~1\Temp\nw4480_11607\node_modules\mysql\lib\Connection.js:108:18)
at Object.mysql.testConnection
Kindly suggest me solution to establish the MySQL connection through node-webkit.
i had the same problem... and downgrading node webkit to the version 0.8.6 did the trick...
i hope this help you...

Cannot connect to live database in Nodejs Openshift Application

I have no trouble connecting to the live database locally using port forwarding, but when we go to connect from the openshift gear, we get errors. Let me begin with the code:
Here is the connection variable
var connectionpool = mysql.createPool({
host : process.env.OPENSHIFT_MYSQL_DB_HOST,
port : process.env.OPENSHIFT_MYSQL_DB_PORT,
user : process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password : process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database : 'stembuds',
socket : process.env.OPENSHIFT_MYSQL_DB_SOCKET
});
Here is an example of a query:
app.get('/answerDB/:course?/:answerID?', function(req, res){
var course = req.param('course');
var answerID = req.param('answerID');
connectionpool.getConnection(function(err, connection){
if(err){
console.error('CONNECTION error: ',err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
}
if (course === undefined && answerID === undefined) {
connection.query('SELECT * FROM questions WHERE counter = 0', function(err, rows, fields){
if (err) {
console.error(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
}
for(var i in rows){
var newCourse = rows[i].course;
newCourse = courses[newCourse];
rows[i].course = newCourse;
}
res.send(rows);
connection.release();
});
}
Here are some errors we receive.
First is an error in the console of Chrome:
GET http://**.rhcloud.com/answerDB 503 (Service Temporarily Unavailable)
But sometimes we get a proxy error:
GET http://**.rhcloud.com/exploreDB 502 (Proxy Error)
Additionally, I have been running the command rhc tail -a nodejs and here is the error I am receiving
CONNECTION error: { [Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'adminMYXaSuf'#'127.11.28.130' (using password: YES)]
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
fatal: true }
TypeError: Cannot call method 'query' of undefined
at /var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/routes/site.js:172:15
at Pool.<anonymous> (/var/lib/openshift/5303aee55973ca4092000084/app- root/runtime/repo/node_modules/mysql/lib/Pool.js:49:16)
at Handshake.Sequence.end (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/sequences/Sequence.js:78:24)
at Handshake.ErrorPacket (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/sequences/Handshake.js:93:8)
at Protocol._parsePacket (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/Protocol.js:202:24)
at Parser.write (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.<anonymous> (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/Connection.js:72:28)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:720:14)
Now it says cannot call method query of undefined. We thought that was strange, so we changed 'connection.query' to 'connectionpool.query' and it then told us that it cannot call method release of undefined. So we changed 'connection.release()' to 'connectionpool.release()' and it told us that the object # has no method release. So I am taking that part of the error with a grain of salt.
We have no idea why it wont connect. Any information would be greatly appreciated - Thanks.
If your application code works locally while connecting to your remote OpenShift-hosted DB (using rhc port-forward), then I would suspect that your app may have some undocumented dependencies.
It could be that you've installed something locally (or globally) in your dev environment, without including that dep in your app's package.json file.
Make sure that everything your app needs in order to run in a fresh environment is included in your app's package.json file before pushing it to OpenShift.
npm install my_dependency --save
I've written up some additional notes that might be useful for testing locally with a port-forwarded connection to an OpenShift-hosted DB: https://www.openshift.com/blogs/set-up-local-access-to-openshift-hosted-services-with-port-forwarding
Did you create that database name? It should be the name of your application. You can use the OPENSHIFT_APP_NAME environment variable for your database name. Can you ssh into your gear and connect to mysql without any issues? Also, are you trying to connect to the database on your openshift gear from your local machine or from your openshift gear?