How to fetch data from MySQL to React html table - mysql

Is there a way to get data from the MySQL database (this can be done whit the Node.js back-end), but I can not create a table from that data in React.js?
Is there a good option to do that?
(I'm creating an electron application whit react and I want to list all the users from the MySQL database)
In PHP is like this https://www.w3schools.com/php/php_mysql_select.asp
var mysql = window.require('mysql');
function Test() {
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
port : 8889,
database : 'loginsystem'
});
connection.connect();
var sql = 'SELECT * FROM users';
connection.query(sql, function (error, results, fields) {
if(error){
console.log(error);
}
if (!results.length){
console.log("error_fetching_data_from_database --",results.length);
}else{
console.log(result)
}
});
const listof = (
//I want print out useres here like table from the database
)
return(listof)
}
export default Test;

Related

Why does this perfectly fine SQL query not work in node.js?

I have the following query that works perfectly fine on MySQL Workbench. I included backticks so that node.js should be able to handle it:
createdb.sql:
CREATE DATABASE IF NOT EXISTS `clients`;
USE `clients`;
CREATE TABLE IF NOT EXISTS `client_data` (
`id` INT NOT NULL AUTO_INCREMENT,
`unique_id` VARCHAR(255),
`uses` TINYINT,
`auth_time` DATE,
`last_cash` MEDIUMINT,
PRIMARY KEY (`id`)
);
The code is simple enough, yet returns a syntax error:
const mysql = require ('mysql')
const dotenv = require('dotenv')
const fs = require ('fs')
dotenv.config()
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : process.env.MYSQL_KEY,
port: 3306
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
let createQuery = fs.readFileSync ('./queries/createdb.sql').toString()
createQuery = createQuery.replace(/(\r\n|\n|\r)/gm, " ");
console.log (createQuery)
connection.query(createQuery, function (error, results, fields) {
if (error) throw (error)
if (results) console.log (results)
if (fields) console.log (fields)
})
I have no idea why this perfectly fine query doesn't work... any ideas?
The mysql driver, by default, doesn't support multiple statement queries due to security concerns (explained here).
You can enable multiple statement support like this:
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : process.env.MYSQL_KEY,
port : 3306,
multipleStatements: true
});

How to create dynamically database connection in Node.js?

I have created API using express.js framework in Node.js server. My database is mysql. i am able to create connection with database. Below is code for connection.
Now i want to create connection dynamically. I have 2 database ( databaseFirst and databaseSecond).
var mysql=require('mysql');
var connection=mysql.createPool({
host:'localhost',
user:'root',
password:'',
database:'databaseFirst'
});
module.exports=connection;
1) User will login using databaseFirst.
2) After successfully login, they will get database name like as databaseSecond.Now all other APIs will use databaseSecond for that logged user.
3) Each API will send database name so they can identify that which database is using for that user.
Kindly help me.
You can do similar :
Here refrence link : 1.stack 2.documents, nodeDBConnection
var connection;
function createConnectionDB (host,dbName,userName,password) {
connection[dbName] = mysql.createConnection({
host : host,
user : userName,
password : password,
database : dbName
});
connection[dbName].connect();
};
// In API when You getting DBName 'db1' you can use
createConnectionDB('localhost','db1','username','password')
connection['db1'].query('SELECT * from < table name >', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection['db1'].end();
////So API when You getting DBName ('db2') you can use
createConnectionDB('localhost','db2','username','password')
connection['db2'].query('SELECT * from < table name >', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection['db2'].end();

Electron MySQL Variable Scope

I am using mysql with Electron.
Here is my code to connect to database. I am in a problem of variable scope. I do google for a long time but found no solution.
What I want to do is described within the uppercase comment inside the code. Please look at the code and give me suggestion if any.
<script>
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: null,
database: 'electron_db'
});
connection.connect();
var sql = 'SELECT `emp_id`,`emp_name` FROM `employee`';
connection.query(sql, function(error, results, fields) {
if (error) console.log(error.code);
else {
console.log(results);
$('#resultDiv').text(results[0].emp_name); //emp_name is column name in your database
// I WANT TO ASSIGN emp_name TO A VARIABLE x AND TO USE IT OUTSIDE THE CALLBACK.
// LIKE THIS
// ASSIGN VARIABLE HERE
x = results[0].emp_name;
}
});
connection.end();
// USE VARIABLE x HERE
$('#resultDiv').text(x);
</script>

How to access mysql db from meteor

Is there a way to import data from MySQL database on Meteor startup? I basically need just an initial data from MySQL to export it to Mongo collections for usage.
Your best bet might be to just use a mysql node package (remember to use Meteor.npmRequire(..) instead of require(..)). This one seems good:
https://github.com/felixge/node-mysql
Something like this should work:
if (Meteor.isServer) {
var mysql = Meteor.npmRequire('mysql');
Meteor.startup(function() {
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
connection.query('SELECT * FROM table', function(err, rows, fields) {
if (err) throw err;
// create documents from rows[i] and add to your collection
});
connection.end();
});
}

Node.js changes in mysql

i have a question regarding about node.js for mysql.
I'm trying to check for changes in the database with node.js and every time it does a change it would do something.
I have the following code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'socialpodd',
});
connection.connect();
connection.query('SELECT * FROM personal', function(err, rows, fields) {
if (err) throw err;
console.log('Rows: ', rows[0].email);
});
connection.end();
But I want this code to be called once there is a change in the database. I know I could do a poll method, but it doesn't seem that effective and real-time. What would be a good real-time module that would allow me to do it, or is polling my only option?