Skip to main content

Connect to SQL with knex

If you want to use knex inside a Spell, you should add these dependencies to your Spell:

Here is a template to interact with the database:

//Connection to database
const db = knex({
client: "mysql",
version: "5.7",
connection: {
host: "myserver.test.com",
port: 3306,
user: "admin",
password: "password",
database: "mydb",
},
});

try {
//Pushing new data to database
//This data can be a array of object, matching with database columns
await db("databaseName").insert(data);
} catch (error) {
console.error(error);
} finally {
//Disconnect the database at the end
db.destroy();
}

We recommend using a try/catch to catch potential database error (like unmatching columns) and a finally to ensure the disconnection to the database.

info

For security reason, you may want to have a static IP for reaching your database (in order to filter access). More information are available here