简体   繁体   中英

Connecting to MySQL through Node.js

I am trying to connect to MySQL database using Javascript through the code I found online:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "Restaurants",
  socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "INSERT INTO customers (name, address) VALUES ('Company    
    Inc', 'Highway 37')";
  con.query(sql, function (err, result) {
  if (err) throw err;
  console.log("1 record inserted");
  });
});

Per online suggestions, I have added the following path to the socket:

socketPath: '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'

Running this file through the Terminal, I get the following error:

Error: connect ELOOP   
/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock
   at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)
  at Protocol._enqueue   
    (/Users/aliaksandrnenartovich/node_modules/mysql
    /lib/protocol/Protocol.js:144:48)
  at Protocol.handshake  
    (/Users/aliaksandrnenartovich/node_modules/mysql
    /lib/protocol/Protocol.js:51:23)
  at Connection.connect (/Users/aliaksandrnenartovich/node_modules
    /mysql/lib/Connection.js:119:18)
  at Object.<anonymous>  
     (/Users/aliaksandrnenartovich/Desktop/JScript/te.js:11:5)
  at Module._compile (module.js:653:30)
  at Object.Module._extensions..js (module.js:664:10)
  at Module.load (module.js:566:32)
  at tryModuleLoad (module.js:506:12)
  at Function.Module._load (module.js:498:3)
  at Function.Module.runMain (module.js:694:10)

I have XAMPP 5.6.33-0 installed, and I can successfully start the Apache server and MySQL database manually, but when I try to connect through Node.js it does not work. I have researched this error online but there seems to be little information as to what may be going on. I understand that this has something to do with mysql.sock file but I am just not sure how to deal with it.

Any suggestions will be greatly appreciated. Thank you in advance!

Have you successfully connected to the database with those credentials/parameters using some SQL client like MySQL Workbench? Just to be sure they are correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM