Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Trying to connect Node.js to MySql database and having issues.

Here is my very basic code. All I'm doing now is trying to get the server to actually connect before I start actually writing tables.

var mysql = require('mysql')

var connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_user',
  password: 'some_secret',
  database: 'the_app_database'
})

connection.connect(function(err) {
  if (err) throw err
  console.log('You are now connected...')
  connection.end();
})

Here is the error that I receive:

C:\Users\Ben\Desktop\Development\Apps\Mochaic\express-react>node database
C:\Users\Ben\Desktop\Development\Apps\Mochaic\express-react\database.js:11
  if (err) throw err
           ^

Error: connect ECONNREFUSED 127.0.0.1:3306
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1097:14)
    --------------------
    at Protocol._enqueue (C:\Users\Ben\Desktop\Development\Apps\Mochaic\express-react\node_modules\mysql\lib\protocol\Protocol.js:144:48)
    at Protocol.handshake (C:\Users\Ben\Desktop\Development\Apps\Mochaic\express-react\node_modules\mysql\lib\protocol\Protocol.js:51:23)
    at Connection.connect (C:\Users\Ben\Desktop\Development\Apps\Mochaic\express-react\node_modules\mysql\lib\Connection.js:119:18)
    at Object.<anonymous> (C:\Users\Ben\Desktop\Development\Apps\Mochaic\express-react\database.js:10:12)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)

1 Answer

jamesjones21
jamesjones21
9,260 Points

Hi Ben, strange thing, but is your local server running mysql? If you have xammp installed, just run sql and then try an connect to the database using node.