Convert Figma logo to code with AI

sidorares logonode-mysql2

:zap: fast mysqljs/mysql compatible mysql driver for node.js

4,029
610
4,029
481

Top Related Projects

18,264

A pure node.js JavaScript Client implementing the MySQL protocol.

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

34,121

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

PostgreSQL client for node.js.

1,570

Node TDS module for connecting to SQL Server databases.

Quick Overview

node-mysql2 is a fast MySQL client for Node.js with focus on performance. It's a continuation of the popular node-mysql project, rewritten from scratch with a focus on better performance and more features. This library is fully compatible with MySQL and MariaDB.

Pros

  • High performance and efficiency compared to other MySQL clients
  • Supports both callback and Promise-based interfaces
  • Fully compatible with MySQL and MariaDB
  • Extensive feature set, including prepared statements and connection pooling

Cons

  • May have a steeper learning curve for beginners compared to simpler MySQL clients
  • Documentation could be more comprehensive and better organized
  • Some advanced features might require more setup or configuration
  • Occasional issues with TypeScript definitions reported by users

Code Examples

  1. Connecting to a MySQL database:
const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

connection.connect((err) => {
  if (err) {
    console.error('Error connecting to the database:', err);
    return;
  }
  console.log('Connected to the database');
});
  1. Executing a simple query:
connection.query('SELECT * FROM users', (err, results, fields) => {
  if (err) {
    console.error('Error executing query:', err);
    return;
  }
  console.log('Query results:', results);
});
  1. Using prepared statements:
const stmt = connection.prepare('INSERT INTO users (name, email) VALUES (?, ?)');
stmt.execute(['John Doe', 'john@example.com'], (err, results) => {
  if (err) {
    console.error('Error executing prepared statement:', err);
    return;
  }
  console.log('Inserted user with ID:', results.insertId);
});

Getting Started

To get started with node-mysql2, follow these steps:

  1. Install the package:

    npm install mysql2
    
  2. Create a connection to your MySQL database:

    const mysql = require('mysql2');
    const connection = mysql.createConnection({
      host: 'localhost',
      user: 'your_username',
      password: 'your_password',
      database: 'your_database'
    });
    
  3. Execute queries:

    connection.query('SELECT * FROM users', (err, results) => {
      if (err) throw err;
      console.log(results);
    });
    
  4. Close the connection when done:

    connection.end();
    

For more advanced usage, refer to the project's documentation on GitHub.

Competitor Comparisons

18,264

A pure node.js JavaScript Client implementing the MySQL protocol.

Pros of mysql

  • More established and widely used in the Node.js ecosystem
  • Extensive documentation and community support
  • Simpler API for basic use cases

Cons of mysql

  • Slower performance compared to mysql2, especially for large datasets
  • Lack of support for newer MySQL features and protocol improvements
  • No built-in connection pooling (requires separate module)

Code Comparison

mysql:

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'db'
});
connection.query('SELECT * FROM users', (error, results) => {
  if (error) throw error;
  console.log(results);
});

mysql2:

const mysql = require('mysql2/promise');
async function query() {
  const connection = await mysql.createConnection({
    host: 'localhost',
    user: 'user',
    password: 'password',
    database: 'db'
  });
  const [results] = await connection.query('SELECT * FROM users');
  console.log(results);
}

The main differences in the code examples are:

  1. mysql2 supports promises out of the box
  2. mysql2 allows for async/await syntax
  3. mysql2 returns results directly, while mysql requires a callback

Both libraries offer similar basic functionality, but mysql2 provides improved performance and support for newer MySQL features, making it a strong choice for new projects or those requiring better performance.

29,432

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

Pros of Sequelize

  • ORM with support for multiple databases (MySQL, PostgreSQL, SQLite, etc.)
  • Built-in data validation and type-checking
  • Provides an abstraction layer for database operations, making it easier to switch databases

Cons of Sequelize

  • Steeper learning curve due to its extensive feature set
  • Can be slower for simple queries compared to raw SQL
  • Adds an extra layer of complexity to the application

Code Comparison

Sequelize:

const User = sequelize.define('User', {
  username: DataTypes.STRING,
  birthday: DataTypes.DATE
});

const users = await User.findAll();

node-mysql2:

const [rows, fields] = await connection.execute(
  'SELECT * FROM `users`'
);

Key Differences

  • Sequelize is a full-featured ORM, while node-mysql2 is a MySQL-specific driver
  • Sequelize provides a higher level of abstraction, whereas node-mysql2 offers more direct control over SQL queries
  • Sequelize supports multiple databases, but node-mysql2 is focused solely on MySQL
  • node-mysql2 may have better performance for simple queries, while Sequelize excels in complex data modeling scenarios

Use Cases

  • Choose Sequelize for large-scale applications with complex data relationships or when database portability is important
  • Opt for node-mysql2 when working exclusively with MySQL and prioritizing performance for simpler database operations
19,158

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

Pros of Knex

  • Query builder with support for multiple databases (MySQL, PostgreSQL, SQLite, etc.)
  • Provides a unified API for database migrations and seeding
  • Offers a promise-based interface for easier async/await usage

Cons of Knex

  • Higher abstraction level may lead to less control over raw SQL queries
  • Steeper learning curve for developers familiar with raw SQL
  • Potential performance overhead due to the abstraction layer

Code Comparison

Knex query:

knex('users')
  .where('id', 1)
  .update({ name: 'John' })

node-mysql2 query:

connection.query(
  'UPDATE users SET name = ? WHERE id = ?',
  ['John', 1]
)

Summary

Knex is a versatile query builder and migration tool supporting multiple databases, while node-mysql2 is a dedicated MySQL driver. Knex offers a higher-level abstraction with a unified API for various database operations, making it easier to switch between different database systems. However, this abstraction comes at the cost of less direct control over SQL queries and a potential performance overhead.

node-mysql2, being a specialized MySQL driver, provides more direct access to MySQL-specific features and potentially better performance for MySQL-only applications. It's generally easier to use for developers already familiar with raw SQL queries but lacks the database-agnostic features and migration tools offered by Knex.

Choose Knex for multi-database support and a unified query-building API, or node-mysql2 for MySQL-specific projects requiring direct query control and optimal performance.

34,121

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Pros of TypeORM

  • Supports multiple databases, not just MySQL
  • Provides an ORM with entity relationships and migrations
  • Offers both Active Record and Data Mapper patterns

Cons of TypeORM

  • Steeper learning curve due to more complex features
  • Potentially slower performance for simple queries
  • Larger package size and more dependencies

Code Comparison

TypeORM:

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

node-mysql2:

const sql = 'SELECT * FROM users WHERE id = ?';
connection.query(sql, [userId], (err, results) => {
  // Handle results
});

TypeORM provides a more declarative approach with decorators for defining entities and relationships, while node-mysql2 offers a lower-level API for direct SQL queries. TypeORM abstracts away database-specific details, making it easier to switch between different databases. However, node-mysql2 gives more control over raw SQL queries and may be more performant for simple operations.

TypeORM is better suited for complex applications with multiple entities and relationships, while node-mysql2 is ideal for projects that require fine-grained control over MySQL-specific features or prioritize raw performance.

PostgreSQL client for node.js.

Pros of node-postgres

  • Native support for PostgreSQL-specific features like JSONB and array types
  • Built-in connection pooling for improved performance
  • Extensive documentation and active community support

Cons of node-postgres

  • Slightly more complex API compared to node-mysql2
  • Limited support for MySQL-specific features
  • Potentially slower performance for simple queries compared to node-mysql2

Code Comparison

node-postgres:

const { Pool } = require('pg');
const pool = new Pool();
const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);

node-mysql2:

const mysql = require('mysql2/promise');
const connection = await mysql.createConnection(config);
const [rows] = await connection.execute('SELECT * FROM users WHERE id = ?', [userId]);

Both libraries offer promise-based APIs, but node-postgres uses a connection pool by default, while node-mysql2 requires explicit connection creation. node-postgres uses numbered placeholders ($1), whereas node-mysql2 uses question marks for parameter substitution.

node-postgres is ideal for PostgreSQL-specific projects, while node-mysql2 is better suited for MySQL databases. The choice between them depends on the specific database being used and the required features for the project.

1,570

Node TDS module for connecting to SQL Server databases.

Pros of tedious

  • Native implementation for SQL Server, optimized for Microsoft's database
  • Supports advanced SQL Server features like Always Encrypted and Azure Active Directory authentication
  • More comprehensive documentation and examples for SQL Server-specific scenarios

Cons of tedious

  • Limited to SQL Server, while node-mysql2 supports MySQL and MariaDB
  • Generally slower performance compared to node-mysql2 for basic operations
  • Steeper learning curve, especially for developers more familiar with MySQL syntax

Code Comparison

node-mysql2:

const mysql = require('mysql2');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  database: 'test'
});
connection.query('SELECT * FROM users', (err, results) => {
  console.log(results);
});

tedious:

const { Connection } = require('tedious');
const config = {
  server: 'localhost',
  authentication: { type: 'default', options: { userName: 'user', password: 'password' } },
  options: { database: 'test' }
};
const connection = new Connection(config);
connection.on('connect', err => {
  if (err) console.error(err);
  else executeStatement();
});

Both libraries provide Node.js drivers for database connectivity, but tedious is specifically designed for SQL Server, while node-mysql2 focuses on MySQL and MariaDB. tedious offers more SQL Server-specific features, while node-mysql2 generally provides better performance for basic operations and has a simpler API for developers familiar with MySQL.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

MySQL2

NPM Version NPM Downloads Node.js Version GitHub Workflow Status (with event) Codecov License

English | 简体中文 | Português (BR)

MySQL client for Node.js with focus on performance. Supports prepared statements, non-utf8 encodings, binary log protocol, compression, ssl much more.

Table of Contents

History and Why MySQL2

MySQL2 project is a continuation of MySQL-Native. Protocol parser code was rewritten from scratch and api changed to match popular Node MySQL. MySQL2 team is working together with Node MySQL team to factor out shared code and move it under mysqljs organization.

MySQL2 is mostly API compatible with Node MySQL and supports majority of features. MySQL2 also offers these additional features:

Installation

MySQL2 is free from native bindings and can be installed on Linux, Mac OS or Windows without any issues.

npm install --save mysql2

If you are using TypeScript, you will need to install @types/node.

npm install --save-dev @types/node

For TypeScript documentation and examples, see here.

Documentation

Acknowledgements

Contributing

Want to improve something in MySQL2? Please check Contributing.md for detailed instruction on how to get started.

To contribute in MySQL2 Documentation, please visit the Website Contributing Guidelines for detailed instruction on how to get started.

NPM DownloadsLast 30 Days