DEV Community

Sh Raj
Sh Raj

Posted on

Creating a Database Connection in Pure JavaScript (Node.js) Without Any Library

Creating a Database Connection in Pure JavaScript (Node.js) Without Any Library

When working with databases in Node.js, developers usually rely on libraries like mysql2, pg, or mongoose for database interactions. However, it's possible to connect to a database without using any external libraries, leveraging Node.js's built-in net module.

In this article, we'll explore how to create a raw database connection using pure JavaScript in Node.js. We'll manually establish a connection to a MySQL database using a TCP socket and send raw SQL queries.


Understanding the Basics

MySQL (and other databases) communicate using the TCP protocol. Instead of using a high-level driver, we can create a direct connection using the built-in net module in Node.js.

Steps to Connect to MySQL Without a Library

  1. Establish a TCP connection to the MySQL server.
  2. Implement the MySQL handshake protocol.
  3. Send authentication packets.
  4. Execute SQL queries manually.

Let's dive into the implementation!


Pure JavaScript MySQL Connection

const net = require("net");

// MySQL Server Configuration
const HOST = "127.0.0.1"; // Change to your MySQL server address
const PORT = 3306; // Default MySQL port
const USER = "root";
const PASSWORD = "";
const DATABASE = "test";

// Create a raw TCP connection
const client = new net.Socket();

client.connect(PORT, HOST, () => {
    console.log("Connected to MySQL Server!");

    // MySQL Handshake (Simplified)
    client.once("data", (data) => {
        console.log("Handshake packet received");

        // Send authentication request (simplified)
        const authPacket = Buffer.from([
            0x0a, // Protocol version
            ...Buffer.from("5.7.31\0"), // Fake server version
            0x01, 0x02, 0x03, 0x04, // Connection ID (random)
            ...Buffer.alloc(8, 0), // 8-byte scramble
            0x00, // Filler
            0xff, 0xff, // Capabilities
            0x21, // Charset
            0x00, 0x00, // Status
            ...Buffer.alloc(13, 0), // Unused bytes
        ]);

        client.write(authPacket);

        client.once("data", (response) => {
            console.log("Authentication Response:", response.toString("hex"));
            executeQuery("SELECT NOW();");
        });
    });
});

// Function to send SQL queries
function executeQuery(query) {
    const queryBuffer = Buffer.from(query + "\0", "utf8");
    client.write(queryBuffer);

    client.once("data", (response) => {
        console.log("Query Response:", response.toString("utf8"));
        client.end();
    });
}

// Handle errors
client.on("error", (err) => {
    console.error("Connection Error:", err);
});

client.on("close", () => {
    console.log("Connection closed");
});
Enter fullscreen mode Exit fullscreen mode

Explanation

  • TCP Connection: We establish a connection using net.Socket() to MySQL’s port (3306).
  • MySQL Handshake: The server sends a handshake packet, and we respond with an authentication request.
  • Query Execution: We manually send an SQL query (SELECT NOW();) and receive the response.
  • Error Handling: The script logs connection errors and closes the socket after execution.

Why Use a Pure JS Connection?

  • Learning Purpose: Understand how database drivers work under the hood.
  • Lightweight Approach: Avoid extra dependencies in minimal applications.
  • Protocol-Level Control: Customize packet structures as needed.

Limitations

  • No Password Authentication: This implementation skips full password hashing.
  • Basic Query Handling: It doesn't handle complex queries or multiple statements.
  • Recommended for Learning Only: For production, use a library like mysql2.

Final Thoughts

While using a database driver is the best approach for real-world applications, this guide demonstrates how Node.js can interact with databases without external libraries. Understanding raw TCP communication helps in debugging and building custom database drivers.

Top comments (0)