Code Icon

Build an app / Node.js + MySQL2

How to connect a Node.js app to SingleStore using MySQL2

on-this-guideOn this guide

This guide walks you through the steps to connect a Node.js application to a SingleStore database using MySQL2. You’ll start by setting up a SingleStore deployment and workspace, then create a database and retrieve your connection credentials. Finally, you’ll configure your Node.js project by installing the mysql2 package, loading environment variables, and establishing a connection to handle queries against your SingleStore instance. By the end, you’ll have a working example that you can use in your application.

prerequisitesPrerequisites

  • SingleStore account
  • Node.js

Don’t have a SingleStore account yet?

Sign up nowArrow Up Right Icon

create-deploymentCreate deployment

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Create NewDeployment.

3. In the Create Workspace form, follow the on‑screen instructions to complete the form.

4. Click Create Workspace.

5. Wait for the workspace to finish deploying.

create-workspaceCreate workspace

Note: If the required workspace already exists in the target deployment, you can skip this step.

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Deployments.

3. From the deployments list, select the deployment where you want to create a workspace.

4. In the left‑hand pane, click + Create Workspace.

5. In the Create Workspace form, follow the on‑screen instructions to complete the form.

6. Сlick Create Workspace.

7. Wait for the workspace to finish deploying.

create-databaseCreate database

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Deployments.

3. From the deployments list, select the deployment where you want to create a database.

4. In the right‑hand pane, click + Create Database.

5. In the Create Database form, enter a new database name and select the workspace to attach it to.

6. Click Create Database.

retrieve-database-credentialsRetrieve database credentials

1. Log in to your SingleStore Portal account.

2. In the left-hand menu, click Deployments.

3. From the deployments list, select the deployment that contains your database.

4. From the workspaces list, select the workspace to which your database is attached.

5. In the selected workspace, click Connect.

6. In the Connect dropdown, choose SQL IDE.

7. In the SQL IDE tab, copy the connection parameters.

If you don’t know the password, click Reset Password, then copy the new password.

prepare-environmentPrepare environment

1. Create a .env file in the root of your project.

2. In this file, define your connection string by adding a DB_URL variable, for example:

1

DB_URL="singlestore://<USER>:<PASSWORD>@<HOST>:<PORT>/<DATABASE_NAME>"

If you don’t know your connection string, see the Retrieve database credentials section above.

3. Now, in a terminal pointing to the root directory of your project, install the mysql2 NPM package by running the following command:

1

npm install mysql2

4. In the same terminal, install and configure dotenv to load your environment variables by running the following command:

1

npm install dotenv

5. Then, you’ll need to import dotenv into your application so you can retrieve the environment variables stored in your .env file. To do this, at the following import statement at the very top of your application entry point (e.g., index.js):

1

import 'dotenv/config'

establish-database-connectionEstablish database connection

In your application entry point, add the following code to establish a database connection:

1

import mysql from "mysql2/promise";

2

3

const db = mysql.createPool(process.env.DB_URL);

You now have everything set up to start querying your database.

query-databaseQuery database

Let’s test to make sure that the connection is working as anticipated. Here is an example of a simple code snippet you can add to your app's main function at the entry point.

1

import "dotenv/config";

2

import mysql from "mysql2/promise";

3

4

const db = mysql.createPool(process.env.DB_URL);

5

6

async function main() {

7

try {

8

console.log("Create users table");

9

const createTableSQL = `

10

CREATE TABLE IF NOT EXISTS users (

11

id BIGINT AUTO_INCREMENT PRIMARY KEY,

12

name VARCHAR(255) NOT NULL

13

)

14

`;

15

16

await db.execute(createTableSQL);

17

18

console.log("Insert user");

19

const insertUserSQL = "INSERT INTO users (name) VALUES (?)";

20

const insertUserResult = await db.execute(insertUserSQL, ["John"]);

21

const insertedUserId = insertUserResult[0].insertId;

22

console.log(insertUserResult);

23

24

console.log("Select all users");

25

const selectUsersSQL = "SELECT id, name FROM users";

26

const selectUsersResult = await db.query(selectUsersSQL);

27

console.log(selectUsersResult);

28

29

console.log("Select user");

30

const selectUserSQL = "SELECT id, name FROM users WHERE id = ?";

31

const selectUserResult = await db.query(selectUserSQL, [insertedUserId]);

32

console.log(selectUserResult);

33

34

console.log("Update user");

35

const updateUserSQL = "UPDATE users SET name = ? WHERE id = ?";

36

const updateUserResult = await db.execute(updateUserSQL, ["John Doe", insertedUserId]);

37

console.log(updateUserResult);

38

39

console.log("Delete user");

40

const deleteUserSQL = "DELETE FROM users WHERE id = ?";

41

const deleteUserResult = await db.execute(deleteUserSQL, [insertedUserId]);

42

console.log(deleteUserResult);

43

} catch (error) {

44

console.error(error);

45

}

46

}

47

48

main();

Once you’ve saved your changes, open a terminal, navigate to your project’s root directory, and run the test script:

1

node ./index.js

This will issue a query against your SingleStore instance, allowing you to see if connectivity was successful or if further troubleshooting is required.

error-handling-and-troubleshootingError handling and troubleshooting

auth-failedAUTH_FAILED

If you receive an AUTH_FAILED exception when trying to establish a connection to database, try the following steps to remedy the issue: