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'
});
Related
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:
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',
I created a React project by entering the following command prompt commands
mkdir mysql-test && cd mysql-test
npm init –y
npm install mysql –save
Then I created a file called app.js and I put in the following code:
// app.js
const mysql = require('mysql');
// First you need to create a connection to the db
const con = mysql.createConnection({
host: 'rds-mysql-wmcw.cgz0te1dlkah.us-east-1.rds.amazonaws.com',
user: 'masterUsername',
password: 'masterPassword',
database : 'db_wmcw'
});
//try to connect to the mySql database. If an error occurs, display an
error message on the console
con.connect((err) => {
if(err){
console.log('Error connecting to Db');
return;
}
//a connection has been established to the database. Now, run a query against the table 'homepage'
//to retrieve each row and all columns of the table
console.log('Connection established');
con.query('SELECT * FROM homepage', (err,rows) => {
//if an error occurs when reading the data from the table, display the error on the console
if(err) {
console.log(err);
return;
}
//data has been retrieved from the table. display the data to the console
console.log('Data received from Db:\n');
console.log(rows);
});
});
con.end((err) => {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
Before I added the con.query command, when I type in app.js at the command prompt, the response back is Connection established. So I know that I am connecting to the mySql database. When I include the con.query command, and I type in app.js at the command prompt, I get the following error:
Connection established
{ Error: Cannot enqueue Query after invoking quit.
at Protocol._validateEnqueue (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:203:16)
at Protocol._enqueue (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:138:13)
at Connection.query (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:200:25)
at Handshake.con.connect (C:\jrs\codercamp\mysql-test\app.js:21:7)
at Handshake. (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:502:10)
at Handshake._callback (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:468:16)
at Handshake.Sequence.end (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Handshake.Sequence.OkPacket (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\sequences\Sequence.js:92:8)
at Protocol._parsePacket (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Parser.js:76:12) code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
Right at the top of the error it states Cannot enqueue Query after invoking quit. I don't understand why the system thinks I am executing the query after invoking quit. I am not invoking quit unless that is what happens when I execute con.end but con.end is the last statement to execute. It is way after the query call.
Any assistance is greatly appreciated.
Thank you.
PS - I have included the host name, user ID, password, and database name to make debugging easier. There is no real important data in the database
Okay, so the alternative solution would be uninstall mysql package and change with mysql2 package instead. As the author said:
MySQL2 is mostly API compatible with mysqljs and supports majority of features
This answer is for the questioner's comment on his post
If you really wanna reassign the one row of data, you can do:
const { product_detail, product_description } = results[0];
That's basic syntax :D (ES6 maybe)
I have installed this database plugin for Node.js called 'db-mysql' and I've gone through all the steps mentioned on the site without getting errors, which must mean that the plugin is installed. But when I run my .js file (given below) in the Apache server I get this error.
Error: Cannot find module 'db-mysql'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/var/www/server.js:4:13)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
Here is the sample code I'm running.
var http = require("http");
var mysql = require("db-mysql");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
//Database Connectivity//
new mysql.Database({
hostname: 'localhost',
user: 'root',
password: '',
database: 'test'
}).on('error', function(error) {
console.log('ERROR: ' + error);
}).on('ready', function(server) {
console.log('Connected to ' + server.hostname + ' (' + server.version + ')');
}).connect();
///////////////////////
response.end();
}).listen(8889);
Did I miss anything during installation?
If you install module like in example
npm install db-mysql
Node will search it here
./project_root/node_modules/db-mysql
So make sure this path is correct in your case.
Other option is to install it globally by using -g flag
npm install db-mysql -g
Simply make a sym link that points to where your modules are physically installed
Name this link node_modules and put it inside the folder of your project
I have a file con_mysql.js with the following content:
var client = require('mysql');
client.createClient({'host':'localhost','port':3306,'user':'root','password':'root'});
client.connect();
then:
# node con_mysql.js
chris:db chris$ node my.js
/Users/chris/node_modules/mysql/lib/client.js:40
throw new Error('deprecated: connect() is now done automatically.');
^
Error: deprecated: connect() is now done automatically.
at Client.connect (/Users/chris/node_modules/mysql/lib/client.js:40:9)
at Object.<anonymous> (/Users/chris/jswork/nodejs/db/con_mysql.js:5:8)
at Module._compile (module.js:446:26)
at Object..js (module.js:464:10)
at Module.load (module.js:353:31)
at Function._load (module.js:311:12)
at Array.0 (module.js:484:10)
at EventEmitter._tickCallback (node.js:190:38)
how can I resolve this problem?
I have installed mysql module like this:
# npm install mysql
deprecated: connect() is now done automatically.
Just try this:
client.createClient({'host':'localhost','port':3306,'user':'root','password':'root'});
The Error above states that it will automatically connect. You don't need to (and obviously cannot) call the connect() function.