Ionut Necula
Ionut Necula

Reputation: 11472

What is the correct way to retrieve data from database using nodejs and MySQL?

I've written a code that should retrieve data from database with nodejs and mysql but it's not working.

It says the I didn't installed the mysql module but I did, using npm install: enter image description here

The proof that I installed the mysql module successfully: enter image description here

Is my code ok ? Keep in mind that I'm completely new to node.js.

var http = require('http');

http.createServer(function(request, response){
	response.writeHead(200, {'Content-Type': 'text/plain'});
	response.write('My first node server...');
		var mysql = require('mysql');
			var connection = mysql.createConnection({
				host :  'localhost:8888',
				user : 'root',
				password: '',
				database: 'test'
			});

			connection.connect();

			connection.query('SELECT * FROM tabel_test', function(err, rows, fields){
					if (!err) {
						console.log('The result is ', rows);
					} else {
						console.log('No results.');
					}
			});

		connection.end();
	response.end();
}).listen(8888);

Upvotes: 3

Views: 3963

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 1

if you found the given path node/node_modules/mysql/lib change the below line connection.query('SELECT * FROM test_user', function(err, rows, fields) connection.end();

Upvotes: 0

meskobalazs
meskobalazs

Reputation: 16041

The code seems fine, the exception says that you do not have the mysql module, that could be technically true.

Make sure you have the node_modules\mysql folder in the current working directory, or that you have installed it globally with npm install -g mysql.

By the way I suggested the package.json file, because in there you could define the required version of the mysql module. Then if you do npm intall in the folder, the enumerated dependencies will be downloaded to the current working directory. This also make it easier for others to use you code, if you put it into a git repository.

Upvotes: 2

Related Questions