nodejs mysql example


Notice: A non well formed numeric value encountered in /home/ghadeerr/public_html/ghadeer.io/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 118

When dealing with databases in NodeJS, mongo seems to be the defacto standard. Many people don’t realize that NodeJS can integrate with databases such as mysql easily and effortlessly.

Let’s take a look at how we can accomplish this using felixge’s node-mysql library.

The first thing we need to do is install the library

Note: The –save after the package name will save the dependency to our package.json.

After installing our package, we need to configure the connection by supplying a username and pasword

Let’s assume that the table we want query against has the following structure

We insert the following records into our database.

Let’s run the following query: Find all records in the ARIN location. Our sql query would look something like this

There is a better way to write this sql query so that the parameters are properly escaped; (very useful when writing complex queries). We can accomplish this by replacing the string ‘Arin’ with a question mark.

The sample above is a good way to execute a sql query but it is not the best pattern to use in production. An enterprise application would reuse a connection from an existing pool of connections.

To create a connection pool, we change

to

The way we execute our queries will change a bit too

Here is a fully working example using connection pooling with promise integration.

You can find a demo project here:

If you enjoyed this article, enter your email below to get free updates!