Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- make sure mySQL workbench is running with your new DB
- // --------------- server.js ---------------------
- //=========== MYSQL CONNECTION ===========
- var mysql = require("mysql");
- // connect to mySQL
- connection = mysql.createConnection({
- host: "localhost",
- port: "3306",
- user: "root",
- password: "root",
- database: 'UserSQL_DB'
- });
- // ======= actually connect ==========
- connection.connect(function(err) {
- if (err) {
- console.error("error connecting: " + err.stack);
- return;
- }
- console.log("connected as id ".yellow + connection.threadId);
- });
- //-------------- controller.js ---------------
- newUser: (req, res) => {
- console.log("req.body.name =>", req.body.name);
- connection.query(`INSERT INTO users (name) VALUES ("${req.body.name}");`, function(err, results_arr, fields) {
- if (err) {
- res.json({message: "Error", err: err});
- throw err;
- } else {
- res.json({message: "Success added to DB", results: results_arr});
- }
- });
- },
- getAll: (req, res) => {
- connection.connect(function(err) {
- // if (err) throw err;
- connection.query("SELECT name FROM UserSQL_DB.users;", function(err, results, fields) {
- if (err) throw err;
- console.log(results);
- res.json({message: "success retreiving all data", results: results});
- })
- connection.end();
- })
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement