Connect with Node. js
On this page
SingleStore is wire-compliant with MySQL.
To connect from Node.
Prerequisites
-
Install (or update to) a supported version of Node.
js (v14 or newer). You can download the Node. js installer from https://nodejs. org/en/download/. -
Install the
mysql2
module as a dependency:npm install --save mysql2
Connection Details
To connect your Node.
-
Host: The IP Address or hostname of your SingleStore cluster.
-
Port: Default is
3306
. -
User: The SingleStore database username, for example,
root
. -
Password: Password of the SingleStore database user.
Here is an example of a Node connection for a cluster:
const db = mysql.createConnection({host: 'localhost',user: 'root',password: 'hjk3874yishf 'database: 'dbExecTest'});
Using Node. js with SingleStore
-
Create a project folder, and initialize this project as an NPM project.
mkdir ss_nodecd ss_nodenpm init -y -
Set up a new cluster.
Refer to the Deploy guide for more information. -
Once the cluster is deployed, set up a new database and create tables.
-
Add the following code block to the
index.
file of your Node application to setup the connection to the new database, using the MySQL2 NPM package.js import mysql from 'mysql2/promise';//Modify the connection details to match the details specified while//deploying the SingleStore cluster:const HOST = 'ip_address_of_the_cluster';const USER = 'root';const PASSWORD = 'root_password';const DATABASE = 'name_of_the_database';// main is run at the endasync function main() {let singleStoreConnection;try {singleStoreConnection = await mysql.createConnection({host: HOST,user: USER,password: PASSWORD,database: DATABASE});console.log("You have successfully connected to SingleStore.");} catch (err) {console.error('ERROR', err);process.exit(1);} finally {if (singleStoreConnection) {await singleStoreConnection.end();}}}main();To connect with Node.
js using SSL, see the Connect with Node. js using SSL topic. -
Run the following command to test the connectivity to your database.
This command executes the index.
file created in the previous step.js node index.jsIf the connection is successful, the following message is displayed:
You have successfully connected to SingleStore.
Examples
The following examples show how to perform basic CRUD operations using Node.messages
table.
CREATE TABLE IF NOT EXISTS messages (id BIGINT AUTO_INCREMENT PRIMARY KEY,content VARCHAR(300) NOT NULL,createdate TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP);
Create Operation
The following example adds a row using the INSERT
command.
async function create({conn, content}) {const [results] = await conn.execute('INSERT INTO messages (content) VALUES (?)',[content]);return results.insertId;};
// call the create() function inside the main() function as:const id = await create({conn, content: 'New message has been logged.'});console.log(`Inserted row id is: ${id}`);
Read Operation
The following example reads the row inserted in the example above.
async function readN({conn, id}) {const [rows] = await conn.execute('SELECT id, content, createdate FROM messages WHERE id = ?',[id]);return rows[0];};
// call the readN() function inside the main() function as:const msg = await readN({conn, id:1});console.log('Read one row:');if (msg == null) {console.log('No message entry with this ID.');} else {console.log(`${msg.id}, ${msg.content}, ${msg.createdate}`);}
Update Operation
The following example updates the row inserted in the Create Operation example above.
async function updateN({conn, content, id}) {await conn.execute('UPDATE messages SET content = ? WHERE id = ?',[content,id]);const [upd] = await conn.execute('SELECT id, content, createdate FROM messages WHERE id = ?',[id]);return upd[0];}
//call the updateN() function inside the main() function as:const i = await updateN({conn, id:1, content: 'This row has been updated.'});console.log(`Updated row id ${i.id}, ${i.content}`);
Delete Operation
The following example deletes the row inserted in the Create Operation example above.
async function deleteN({conn, id}) {await conn.execute('DELETE FROM messages WHERE id = ?',[id]);}
//call the deleteN() function inside the main() function as:await deleteN({conn, id:1});
More Information
-
To build a SingleStore application using JavaScript and Node.
js, refer to the following training: Building a SingleStore Application Using Javascript and Node. js -
Using Stored Procedures: GitHub
-
Using ORM: GitHub
In this section
Last modified: July 19, 2024