How can I query MySQL with node.js? - javascript

I am going to make a client-server application using Node.js, and I want to use a MySQL database for storing some of the data. I need to know how to query a database with server-side JavaScript.

Search the module library for mysql and you will get many modules that will let you do that including mysql, db-mysql, and easy-mysql.

npm install node-mysql
var mysql = require('mysql'),
client = mysql.createClient({
user: 'root',
password: 'root',
});
mysql.query('SELECT * FROM my_table', function(err, results, fields) {
//have fun
client.end();
});
There are other libraries as well that all have slightly different APIs.

Related

How can i solve this error when i use mysql module?

I use the node module to connect my local database, then log this error message:
Client does not support authentication protocol requested by server; consider upgrading MySQL client
next is my configuration:
const mysql = require("mysql");
const db = mysql.createPool({
host: "127.0.0.1",
user: "root",
password: "root",
database: "my_db_01"
});
db.query('select 1', (err, results)=>{
if (err) return console.log(err.message);
console.log(results);
});
I can make sure the configuration is correct.
This looks like a frequent issue in the bug reports for the mysql module.
That module hasn't had a commit since 2020. It has 172 open issues. I would consider it abandoned.
Use a different database module. mysql2 seems to be popular.

Using MySQL with Javascript (node.js)

I've just started learning Node.js. I come from a PHP background, so I started with MySQL.
So, I wanted to try executing some basic MySQL queries using javaScript.I write the queries, this way:
filename: test.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test",
});
con.connect(err => {
if (err) throw err;
console.log("Connected!");
const q = "INSERT INTO testing VALUES(3, 'MILLENNIAL', 19, 'STUDENT', 'CSE')";
con.query(q, (err, result) => {
if (err) throw err;
console.log("done");
});
});
When I run the only the javascript file this way: node test.js the query gets executed but when I connect the same file to a html file, this way:
<script src="test.js"></script>
the query doesn't get executed... It gives an error in console: Uncaught ReferenceError: require is not defined
I have feeling that I am not using something very important here. Am I missing something?? Please help me go further.
I am so sorry if this is very silly but, please help me with this. Thank you in advance.
node.js is javascript runtime which uses javascript syntax, which is meant for server-side language. What you trying is to use nodejs script in frontend. require is not defined - because its applicable only for node, to use other modules in plain javascript you will need to use cdn or packages like browserify, webpack. Checkout docs if you are interested.
I will try to explain from a PHP perspective.
When you write PHP, usually your resulting file is an HTML and you embed your PHP code in it, so it renders out without PHP to the requesting browser.
In node, this is different. We don't write the HTML with node code embedded. Node focuses more on backend and frontend separation. You write your backend to reply to your front end.
The backend is where you type var mysql = require('mysql');
You can use something like express vs koa to serve the resulting query to the front end.
Here's a good tutorial to start https://geshan.com.np/blog/2020/11/nodejs-mysql-tutorial/
I usually recommend Koa because it's up updated more regularly now, but express is basically the same thing!
Hope this directs you in the right direction.

Database connection works in node.js file but not in script tags

I'm trying to connect to my MongoDB database (or to the server actually MongoLab), it works fine when I have the code in name.js file but it doesn't work when I have it in HTML file inside <script> tags.
Also, I only have those 2 files in my folder, and I'm using Cloud9 framework.
This is my JavaScript code:
// JavaScript File
var MongoClient = require('mongodb').MongoClient;
var url = "x";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mkndb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("test").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
Thank you
The package mongodb you are requiring is a node.js package, it runs only on the server side and not in the browser.
To access a MongoDB on the client side, you can use the REST webservice.
It allows rudimentary queries through XmlHttpRequests.
To enable it, you have to start mongod with the --rest parameter.
Then you can then query it like this:
http://127.0.0.1:28017/someDatabase/someCollection/?filter_name=someFilter
You seem to be using the Mongodb node client. Inserting the script in html page with tags would not work in the same way as you expect. You have few ways to achieve what you are looking for :
1. You can build a nodejs server component which can handle the requests from browser application. The nodejs server then interacts with mongodb and respond. This again can be achieved in few ways.
a. Deploy nodejs in Lambda. Mode details here - https://docs.aws.amazon.com/cloud9/latest/user-guide/lambda-functions.html . You can then connect from the browser as given here - https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/browser-invoke-lambda-function-example.html
b. Deploy in EC2
2. If you do not want to build/deploy the node.js server, try using the mLab Data API. (http://docs.mlab.com/data-api/) . This works only for this special case where you are trying to connect to MongoLab

To connect create-react-app reactJs with mysql

I have problem in connecting my create-react-app with mysql using npm.
Its working in nodejs when i tried seperately without npm. But, When i trying to connect using npm install mysql, It throws me an error...
TypeError: http.IncomingMessage is undefined
./node_modules/express/lib/request.js
Here is my code:
var express = require('express');
var mysql = require('mysql');
var connection =mysql.createConnection({
host: 'localhost',
user: 'user',
password: '',
database: 'reactproject'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
This will not work from react-app, since react code will run from client side.
You should use my-sql connection in different app and run in different port and call as api connection.
Thanks.
Adding from an #ashik answer is correct, but if you still want to use MySQL and reactjs simultaneously, you can start by creating your own boilerplate, there you can use MySQL on the server side and create APi/web service without having to separate the APi server and client projects reactjs.

Node.js: accessing mysql database

I am writing a Node.js application. In my node-modules/abc/static/example.js file, I want to access the mysql records by querying to the database. Is it possible to do so?
When I include mysql like this:
var mysql = require('mysql');
I get an error:
Uncaught ReferenceError: require is not defined
Is it because it is on client side? What are the other options to access mysql database from the 'example.js' file?
I'm going to guess that you're attempting to use server side js in the client side.
You need to npm install a mysql adapter, #coreyg suggested this one (https://www.npmjs.com/package/mysql).
Set up a nodejs project (if you have not already done so):
npm init
npm install --save mysql
You would then typically create some sort of webapp that would serve up a url in the client side. You'd then (using ajax) request the url.
Behind the scenes your webapp then would query the mysql database (using the adaptor you installed) with whatever query you had in mind.
Once your ajax call had finished you'd run your callback which would do what you wanted with the data that had been returned from the database.
Thats the basic theory. If you want further information on how to do this I'd suggest reading this question: How do I get started with Node.js
Following on Neil Munro's Answer,
after initiating nodejs and installing mysql npm package,
you can actually execute your code from the terminal. to do that,
you can create a new js file on the same folder you are executing those commands,
say mysqlTestProject.js
inside this file, you can put what you had previously, (require stuff and all). for example:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
`` codes were taken from https://www.npmjs.com/package/mysql
and then from the terminal (still on the same folder as you were),
type in this line
node ./mysqlTestProject.js

Categories