node multiple ways to connect to mysql

In Node.js, there are multiple ways to connect to a MySQL database. Here are a few commonly used methods:

1. Use the mysql module:

mysql is a popular third-party module that can be installed via npm. You can use the createConnection() method provided by this module to create a database connection and execute SQL queries and operations through the connection. Here is a sample code:

const mysql = require('mysql');

const connection = mysql.createConnection({<!-- -->
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

connection.connect((err) => {<!-- -->
  if (err) {<!-- -->
    console.error('Error connecting to MySQL database:', err);
    return;
  }
  console.log('Connected to MySQL database.');

  // Execute database queries and operations here

  connection. end();
});

In the above code, use the createConnection() method to create a database connection, passing in the connection configuration parameters (such as host name, user name, password, and database name). Then connect to the database through the connect() method, and process the connection result in the callback function. After a successful connection, database queries and operations can be performed in the callback function. Finally, use the end() method to close the database connection.

2. Use the mysql2 module:

mysql2 is a more performant MySQL client that can also be installed via npm. Similar to the mysql module, you can use the createConnection() method to create a database connection and execute SQL queries and operations through that connection. Here is a sample code:

const mysql = require('mysql2');

const connection = mysql.createConnection({<!-- -->
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

connection.connect((err) => {<!-- -->
  if (err) {<!-- -->
    console.error('Error connecting to MySQL database:', err);
    return;
  }
  console.log('Connected to MySQL database.');

  // Execute database queries and operations here

  connection. end();
});

Similar to the method of using the mysql module, create a database connection through the createConnection() method, and process the connection result in the callback function. After a successful connection, database queries and operations can be performed in the callback function. Finally, use the end() method to close the database connection.

3. Using an ORM (Object Relational Mapping) library:

The ORM library can map database tables into JavaScript objects, providing a more convenient operation interface. Commonly used ORM libraries include Sequelize, TypeORM and Knex.js, etc. Here is sample code using the Sequelize ORM library:

const Sequelize = require('sequelize');

const sequelize = new Sequelize('database_name', 'username', 'password', {<!-- -->
  host: 'localhost',
  dialect: 'mysql'
});

sequelize. authenticate()
  .then(() => {<!-- -->
    console.log('Connected to MySQL database.');

    // Execute database queries and operations here

    sequelize. close();
  })
  .catch((err) => {<!-- -->
    console.error('Error connecting to MySQL database:', err);
  });

In the above code, first create a Sequelize instance and pass in the database connection configuration parameters. Then use the authenticate() method to verify the connection is successful, and handle the connection result in the then() method. After a successful connection, database queries and operations can be performed in the then() method. Finally, use the close() method to close the database connection.

4. Using Egg.js

If you use the Egg.js framework to develop Node.js applications and connect to the MySQL database, you can use the plug-in egg-mysql provided by Egg.js to simplify database operations. Here are the steps to connect to MySQL database using Egg.js:

  1. Install the egg-mysql plugin: In your Egg.js project directory, use the following command to install the egg-mysql plugin:
$ npm install egg-mysql --save
  1. Configure the database connection: In the config/config.default.js file of the Egg.js project, add the following configuration to configure the database connection:
exports.mysql = {<!-- -->
  // Single database configuration information
  client: {<!-- -->
    // database type
    type: 'mysql',
    // host address
    host: 'localhost',
    // The port number
    port: '3306',
    // username
    user: 'username',
    // password
    password: 'password',
    // Database name
    database: 'database_name',
  },
  // Whether to load it on the app, it is enabled by default
  app: true,
  // Whether to load it on the agent, it is closed by default
  agent: false,
};

Modify the host address, port number, user name, password and database name in the above configuration according to your actual situation.

  1. Use the database: In the Controller or Service of Egg.js, you can use app.mysql to get the database connection and execute SQL queries and operations. Here is a sample code:
const Controller = require('egg').Controller;

class UserController extends Controller {<!-- -->
  async index() {<!-- -->
    const {<!-- --> ctx, app } = this;
    const result = await app.mysql.query('SELECT * FROM users');
    ctx.body = result;
  }
}

module.exports = UserController;

In the above code, the SQL query is executed through the app.mysql.query() method, and the query result is returned in ctx.body. You can use other database operation methods according to actual needs, such as app.mysql.get(), app.mysql.insert(), app.mysql. update() etc.

  1. Use Sequelize: If you want to use Sequelize ORM to connect and operate MySQL database, you can use the plugin egg-sequelize provided by Egg.js. You can follow the above steps to install and configure the egg-sequelize plugin, and use app.model in the Controller or Service of Egg.js to get the Sequelize model and perform database queries and operation.

Advantages and disadvantages and usage scenarios:

  1. Use the native mysql module:

    • Advantages: The native mysql module is an official module provided by Node.js, which is simple and intuitive to use, and is sufficient for simple database operations.
    • Disadvantages: It needs to manually write SQL statements, which is not intuitive and easy to use. For complex database operations, you need to handle connection pools, transactions, and other issues yourself.
    • Usage scenarios: Suitable for simple database operations, for scenarios that require flexible control of database connections and transactions.
  2. Using an ORM (Object Relational Mapping) library:

    • Advantages: The ORM library can map database tables to JavaScript objects, providing a more convenient operation interface. Database operations can be performed in an object-oriented manner without manually writing SQL statements.
    • Disadvantages: The learning cost of the ORM library is high, and you need to be familiar with its usage and API. For simple database operations, there may be some performance overhead.
    • Usage scenarios: It is suitable for scenarios that require complex database queries and operations, or want to perform database operations in an object-oriented manner.
  3. Using the Egg.js plugin:

    • Advantages: The plug-ins provided by Egg.js can simplify the configuration and use of database connections and operations. Database connection information can be managed through configuration files, no need to manually write connection codes.
    • Disadvantage: For complex database operations, complex SQL query statements may need to be written. Familiarity with the Egg.js framework and plugins is required.
    • Usage scenario: It is suitable for projects developed using the Egg.js framework, and the scenario where you want to simplify the configuration and use of database connections and operations.

According to the above advantages and disadvantages and usage scenarios, you can choose the method of connecting to the MySQL database that suits your project needs. If your project requirements are relatively simple, you can use the native mysql module; if you want to use a more convenient operation interface, you can choose to use the ORM library; if you use the Egg.js framework to develop projects, you can use Egg.js provides plugins to simplify database operations.