Skip to content

Instantly share code, notes, and snippets.

@cyb3rsalih
Last active November 26, 2019 00:47
Show Gist options
  • Select an option

  • Save cyb3rsalih/d73bdc3abefdd7e835f376e98bf44373 to your computer and use it in GitHub Desktop.

Select an option

Save cyb3rsalih/d73bdc3abefdd7e835f376e98bf44373 to your computer and use it in GitHub Desktop.
mysql connection with nodejs. Use url path as parameter.
//REF: https://dev.to/saulojoab/how-to-get-data-from-an-mysql-database-in-react-native-53a4
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const connection = mysql.createPool({
host: "localhost", // Your connection adress (localhost).
port: 8889, // 3309 , 8888, 8080 ....
user: "user", // Your database's username.
password: "password", // Your database's password.
database: "db", // Your database's name.
queueLimit: 0, // unlimited queueing
connectionLimit: 0, // unlimited connection,
socketPath: "/../mysql/mysql.sock" // IMPORTANT
});
// Starting our app.
const app = express();
app.use("/", function(req, res) {
// Connecting to the database.
let route = req.url.split("/")[1];
connection.getConnection(function(err, connection) {
if (!err) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query("SELECT 1+1 AS " + route, function(
error,
results,
fields
) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results);
});
} else {
console.log(err);
}
});
});
// Starting our server.
app.listen(3000, () => {
console.log("Go to http://localhost:3000/users so you can see the data.");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment