Attempting to connect to mysql database - mysql

Let me start off by saying that I am a complete beginner with javascript. I am trying to read up on it and learn it. I have a MySQL database hosted with GoDaddy and am attempting to connect to it with a discord bot. Here is the code below:
const Discord = require('discord.js');
const client = new Discord.Client();
var mysql = require('mysql');
var con = mysql.createConnection({
host : 'redacted',
port : 'redacted'
user : 'redacted',
password : 'redacted',
database : 'redacted'
});
con.connect(error => {
if(error) throw error;
msg.channel.send("Connection to database successful!");
});
client.login('redacted');
When I run node index.js, the error is:
user : 'redacted',
^^^^
SyntaxError: Unexpected identifier
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
I don't understand why "user" is an unexpected identifier. Can anyone steer my in the right direction?
Thank you for your time.

You have left off the comma after the redacted port.

You forgot the comma , in the previous line of code
port : 'redacted',

Related

How to connect azure mysql server with nodeJS

I am trying to connect to a remote mysql server with nodejs
So far I am able to connect with mysql workbench 8.0, so no problem with mysql server. And I can easily connect to my local mysql-server (with "mysql2" module).
Here is something I've been trying to connect with remote mysql server provided by Azure. I followed the guides that is provided.
const mysql = require("mysql");
const fs = require("fs")
var connection = mysql.createConnection({
host: process.env.MYSQL_SERVER_HOST,
user: process.env.MYSQL_SERVER_USER,
password: process.env.MYSQL_SERVER_PASSWORD,
database: process.env.MYSQL_SERVER_DATABASE,
port:3306,
ssl: { ca: fs.readFileSync("./certificates/DigiCertGlobalRootCA.crt.pem")}
});
// This is how I am connecting to my local mysql-server which is working fine
// // const connection = mysql.createConnection({
// host: 'localhost',
// user: 'root',
// password: process.env.LOCAL_MYSQL_SERVER_PASSWORD,
// database: 'db',
// port: '3306'
// });
connection.connect((error) => {
if (error) {
console.log("mysql error")
console.log(error)
}
else {
console.log("Mysql Ready")
}
});
module.exports = connection;
Here I am using mysql package because many articles on web suggested it but I even used mysql2 and nothing happened. I even changed the networking setting and allowed my IP address for access(this wasn't necessary though).
Error logs:
mysql error
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (path\node_modules\mysql\lib\Connection.js:409:13)
at Object.onceWrapper (node:events:641:28)
at Socket.emit (node:events:527:28)
at Socket._onTimeout (node:net:516:8)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
--------------------
at Protocol._enqueue (path\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (path\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (path\node_modules\mysql\lib\Connection.js:116:18)
at Object.<anonymous> (path\packnary\database\mysql.js:26:12)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
}
I connected Azure SQL database to the nodejs without using code.
I followed below procedure:
I have created azure blank nodeJs webapp in visual studio.
It run successfully. after that I go to overview of the webapp and selected connected services and clicked on a add a service dependency option and searched for azure sql database.
Image for reference:
select the azure sql data and click on next button.
login to azure account and select which database we need to connect.
Image for reference:
Enter the details required in the next window and click on next.
Image for reference:
Select the changes according to the requirements and click on next.
Image for reference:
It is connected successfully.
Image for reference:

Node.js "Error: connect ECONNREFUSED 127.0.0.1:3306" when trying to connect to MySQL database

I'm a novice at node.js and I want to create an API which sends data to a MySQL server to store them.
I followed a youtube tutorial to create a connection with a MySQL database, also checked other tutorials just to be sure, but I always get this error message when my code tries to connect to MySQL. I used XAMPP first, and then tried downloading and using MySQL from mysql.com, but got the same error.
/home/broken/mysql_projekt/app.js:24
throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16)
--------------------
at Protocol._enqueue (/home/broken/mysql_projekt/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/home/broken/mysql_projekt/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/home/broken/mysql_projekt/node_modules/mysql/lib/Connection.js:116:18)
at Object.<anonymous> (/home/broken/mysql_projekt/app.js:22:4)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
I tried the suggested solutions at other questions but I didn't succeed.
Here's what I tried:
Changing localhost to 127.0.0.1 in the connection configuration.
Check in services.msc if the MySQL service is in a running state.
Tried to add firewall rules to allow outbound and inbound access on
port 3306.
Create another user aside from root with a password with all
privileges, and try to connect with that.
Also tried to add "socketPath: '/var/run/mysqld/mysqld.sock'" to my
connection configuration, as someone in another
question
said that it seemed to solve other's problem, but they just got a
different error message, just like me. (unfortunately I couldn't really understand what it does)
Also tried on another computer, but of course the issue still
remained.
Tried to specify the port number to 3306 in the connection
configuration.
Here is my code:
var express = require('express');
var mysql = require('mysql');
var PORT = 3000;
var app = express();
app.listen(
PORT,
() => {console.log(`Server started on port ${PORT}`)
})
//Creating MySQL connection
var db = mysql.createConnection({
host : "localhost",
user : "user",
password : "password"
//socketPath: '/var/run/mysqld/mysqld.sock'
});
//Connecting
db.connect((err) => {
if(err){
throw err;
}
console.log('MySQL connected');
});
If someone has figured it out, could you share the solution? Thank you!

Connecting to MySQL through Node.js

I am trying to connect to MySQL database using Javascript through the code I found online:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "Restaurants",
socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name, address) VALUES ('Company
Inc', 'Highway 37')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
Per online suggestions, I have added the following path to the socket:
socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
Running this file through the Terminal, I get the following error:
Error: connect ELOOP
/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)
at Protocol._enqueue
(/Users/aliaksandrnenartovich/node_modules/mysql
/lib/protocol/Protocol.js:144:48)
at Protocol.handshake
(/Users/aliaksandrnenartovich/node_modules/mysql
/lib/protocol/Protocol.js:51:23)
at Connection.connect (/Users/aliaksandrnenartovich/node_modules
/mysql/lib/Connection.js:119:18)
at Object.<anonymous>
(/Users/aliaksandrnenartovich/Desktop/JScript/te.js:11:5)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
I have XAMPP 5.6.33-0 installed, and I can successfully start the Apache server and MySQL database manually, but when I try to connect through Node.js it does not work. I have researched this error online but there seems to be little information as to what may be going on. I understand that this has something to do with mysql.sock file but I am just not sure how to deal with it.
Any suggestions will be greatly appreciated. Thank you in advance!
Have you successfully connected to the database with those credentials/parameters using some SQL client like MySQL Workbench? Just to be sure they are correct.

Error as connect ECONNREFUSED when using node.js and MySQL

I'm trying to create a link between node.js and mysql. I get an error as connect ECONNREFUSED. how to solve ths?
CODE:
var mysql = require('mysql');
var conn = mysql.createConnection({
host : "192.164.0.114",
user : "supriya",
password : "root123#",
database: "student"
}
);
var queryString = "SELECT * FROM studata";
conn.query("someurlhere",queryString, function(error, results)
{
if(error)
{
throw error;
}
else {
console.log(results);
}
})
conn.end();
Error is:
Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
--------------------
at Protocol._enqueue (/home/supriya/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/home/supriya/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/home/supriya/node_modules/mysql/lib/Connection.js:109:18)
at Connection._implyConnect (/home/supriya/node_modules/mysql/lib/Connection.js:387:10)
at Connection.query (/home/supriya/node_modules/mysql/lib/Connection.js:174:8)
at Object.<anonymous> (/home/supriya/node_js/example2.js:19:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
I had the same problem. I invoked node server.js, which says
It's Started on PORT 3000 Problem with MySQLError: connect
ECONNREFUSED
By first line, I assumed, intially, it starts mysql server. However, that is not the case. it starts node server, which tries to connect to mysql server and node server says ECONNREFUSED. Clearly, mysql server was not running. I found this, when I logged in, as root, in mysql workbench and tried to execute simple query. There in the corner it said, "..at port 3306, it is not connected" or sth like that.
So, conclusion is starting server.js on some port starts node server and not mysql server.

node refuses to find mysql from script

I want to achieve that node prints me a table from MySql on my Windows 7 (64bit) machine but fail. Sorry for the long post in advance, I tried to be complete, also I failed to find this error in the forum. The optimistic mysql.js file I typed in Notepad++ was
var mysql = require('node-mysql');
var connectParams = {'hostname' : 'localhost','user' : 'dev','password': 'dev','database' : 'upandrunning'};
var db = new mysql.Database(connectParams);
db.connect( function(err) {
if(err) return console.log('Failed to connect ' + err);
this.query()
.select(['id', 'user_login'])
.from('users')
.execute(
function(err, rows, columns){
if(err) return console.log('err on query ' + err);
console.log(rows);
})});
Node keeps returning
C:\dev\nodejs\0.10\tutorials\node-up-and-running>node tutorials\node-up-and-running\mysql.js
module.js:340
throw err;
^
Error: Cannot find module 'C:\dev\nodejs\0.10\tutorials\node-up-and-running\tutorials\node-up-and-running\mysql.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
Why??
Before the node command I told Squirrel to do
drop database if exists upandrunning;
create database upandrunning;
grant all privileges on upandrunning.* to 'dev'#'%' identified by 'dev';
use upandrunning;
create table users(
id int auto_increment primary key,
user_login varchar(25),
user_nicename varchar(75)
);
using my localhost root account (bad), but all seemed fine because squirrel object tab showed new upandrunning db.
Node.exe is on C:\dev\nodejs\0.10\ but from dos prompt:
C:\dev\nodejs\0.10\tutorials\node-up-and-running>node -v
gives
v0.10.26
My file mysql.js has been reduced to the mere
var mysql = require('node-mysql');
where the error must be. I ran the following commands from C:\dev\nodejs\0.10\tutorials\node-up-and-running>
npm install -g mysql
npm install -g node-mysql
npm install -g db-mysql
These were the ones i could find.
After each install the same error above.
Any suggestions please how to make node cooperate?
I admit I lack node trouble shooting skills, but studying module.js, should not be necessary.
Also, do you know of, and enjoy working in, a free and easy to work with code completion ide for node?
And is there some way to debug other than console.log() ?.
Lastly what are your ideas on layout conventions for reducing the closing brackets because they hurt the eyes.
The site suggested From NodeJS require a global module/package
but how do i get the node_path variable on dos prompt and how to set it:
C:\dev\nodejs\0.10\tutorials\node-up-and-running>set NODE_PATH
Environment variable NODE_PATH not defined
Ok set NODE_PATH=c:\dev\nodejs\0.10
C:\dev\nodejs\0.10\tutorials\node-up-and-running>node tutorials\node-up-and-running\mysql.js
'node' is not recognized as an internal or external command, operable program or batch file.
Closing and reopening dos makes this go away.
C:\dev\nodejs\0.10>set NODE_PATH=%NODE_PATH%;C:\dev\nodejs\0.10\node_modules
And it works.. But now it fails on
var mysql = require('mysql');
var connectParams = {'hostname' : 'localhost','user' : 'dev','password': 'dev','database' : 'upandrunning'};
var db = new mysql.Database(connectParams);
C:\dev\nodejs\0.10\mysql.js:3
var db = new mysql.Database(connectParams);
^
TypeError: undefined is not a function
at Object.<anonymous> (C:\dev\nodejs\0.10\mysql.js:3:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
and if i remove the new it says
C:\dev\nodejs\0.10\mysql.js:3
var db = mysql.Database(connectParams);
^
TypeError: Object # has no method 'Database'
at Object. (C:\dev\nodejs\0.10\mysql.js:3:17)
Using the REPL:
var mysql = require('mysql');
undefined
var connectParams = {'hostname' : 'localhost','user' : 'dev','password': 'dev'
,'database' : 'upandrunning'};
undefined
var db = new mysql.Database(connectParams);
TypeError: undefined is not a function
at repl:1:10
at REPLServer.self.eval (repl.js:110:21)
at repl.js:249:20
at REPLServer.self.eval (repl.js:122:7)
at Interface. (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
Aren't you supposed to create the connection like this.. ?
connection = mysql.createConnection({
host : 'localhost',
user : 'node',
password : 'UnPassword',
database: 'nodesql'
});