how to connect mysql with react js code example
Example 1: how to manage a db connection in javascript
const mysql = require('mysql2');
const connection = mysql.createPool({
host: "localhost",
user: "",
password: "",
database: ""
});
module.exports = connection;
const connection = require('../util/connection');
async function getAll() {
const sql = "SELECT * FROM tableName";
const [rows] = await connection.promise().query(sql);
return rows;
}
exports.getAll = getAll;
Example 2: use nodejs mysql
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 (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution);}); connection.end();
Example 3: connect to mysql using react js
module.exports = {
HOST: "localhost",
USER: "root",
PASSWORD: "123456",
DB: "testdb",
dialect: "mysql",
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};