How to connect express to mysql aiven?

const express = require(‘express’);
const cors = require(‘cors’);
const mysql = require(‘mysql’);
const app = express();
const port = 18936;

// Middleware
app.use(cors());
app.use(express.json());

// Create a connection to the database
const db = mysql.createConnection({
host: “aiven.com”,
user:" "
password: “”,
database: "name ",
});

// Connect to the database
db.connect((err) => {
if (err) {
console.error('Database connection error: ', err);
process.exit(1);
}
console.log(‘Connected to the database’);
});

Hey Rajesh,

If this is in regards to the “Quick connect” examples we provide on the console, as we do not have one for NodeJS in case of MySQL.

Something like below (using mysql2 package instead of mysql ) could work.

const mysql = require('mysql2');

const config = {
  user: 'avnadmin',
  password: '************************',
  host: 'mysql-8ca9016-testproject-gqmw-john-doe-test.avns.net',
  port: 14421,
  database: 'defaultdb',
  ssl: {
    rejectUnauthorized: true,
    ca: `-----BEGIN CERTIFICATE-----
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************************
****************************************************
-----END CERTIFICATE-----`,
  },
};

const connection = mysql.createConnection(config);

connection.execute('SELECT VERSION() AS version', [], function (err, result) {
  if (err) throw err;

  console.log(result[0].version);
});

connection.end();```

Hope that helps! Take care.