Nodejs连接MySQL数据库模块mysql的使用

Nodejs连接MySQL数据库模块mysql的使用
在Node.js中连接和操作MySQL数据库,可以使用mysql模块。下面我将详细介绍如何安装这个模块以及如何进行基本的操作。

1. 安装mysql模块

首先,你需要通过npm(Node Package Manager)来安装mysql模块。打开命令行工具,然后运行以下命令:

npm install mysql

2. 连接到MySQL数据库

安装完成后,你可以使用以下代码来连接到MySQL数据库:

const mysql = require('mysql');

// 创建一个连接池
const pool = mysql.createPool({
    host: 'localhost',       // 数据库地址
    user: 'root',            // 用户名
    password: 'yourpassword',// 密码
    database: 'testdb'       // 数据库名称
});

// 使用连接池连接数据库
pool.getConnection((err, connection) => {
    if (err) throw err;
    console.log('Connected!');
    
    // 使用连接对象执行SQL查询
    connection.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
        if (error) throw error;

        console.log('The solution is: ', results[0].solution);
        
        // 结束连接
        connection.release();
    });
});

3. 执行SQL语句

插入数据

pool.query('INSERT INTO users SET ?', {name: 'John Doe', age: 25}, (error, results, fields) => {
    if (error) throw error;
    console.log("Inserted row with ID:", results.insertId);
});

查询数据

pool.query('SELECT * FROM users WHERE name = ?', ['John Doe'], (error, results, fields) => {
    if (error) throw error;
    console.log("Found rows:", results);
});

更新数据

pool.query('UPDATE users SET age = ? WHERE name = ?', [30, 'John Doe'], (error, results, fields) => {
    if (error) throw error;
    console.log("Updated rows count:", results.affectedRows);
});

删除数据

pool.query('DELETE FROM users WHERE name = ?', ['John Doe'], (error, results, fields) => {
    if (error) throw error;
    console.log("Deleted rows count:", results.affectedRows);
});

4. 错误处理

在实际应用中,你应该添加更多的错误处理逻辑来确保应用程序的健壮性。例如,在每次查询后检查是否有错误发生,并采取适当的措施。

以上就是使用Node.js和mysql模块连接MySQL数据库并进行基本CRUD操作的方法。希望这对你有所帮助!


3 回复

要使用Node.js连接MySQL数据库,你需要先安装mysql模块。可以通过运行npm install mysql来安装。

然后你可以这样使用:

const mysql = require('mysql');

// 创建一个连接
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'yourusername',
  password: 'yourpassword',
  database: 'yourdatabase'
});

// 连接到数据库
connection.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  
  // 执行SQL查询
  connection.query('SELECT * FROM users', function (error, results, fields) {
    if (error) throw error;
    console.log('The solution is: ', results[0].solution);
  });
});

// 关闭连接
connection.end();

祝你在Node.js和MySQL的世界里玩得开心!记得处理好错误哦,不要让bug偷走你的快乐!


mysql 是 Node.js 中用于连接和操作 MySQL 数据库的一个非常流行的模块。下面我会详细介绍如何安装这个模块以及一些基本的使用方法。

1. 安装 mysql 模块

首先,你需要在你的项目中安装 mysql 模块。你可以通过 npm(Node 包管理器)来安装:

npm install mysql

2. 连接到 MySQL 数据库

接下来,你需要创建一个数据库连接。以下是一个简单的示例:

const mysql = require('mysql');

// 创建连接
const connection = mysql.createConnection({
    host: 'localhost',       // 数据库服务器地址
    user: 'root',            // 用户名
    password: 'yourpassword',// 密码
    database: 'yourdatabase' // 要使用的数据库
});

// 打开连接
connection.connect((err) => {
    if (err) {
        console.error('Error connecting to the database:', err.stack);
        return;
    }
    console.log('Connected as id ' + connection.threadId);
});

3. 执行 SQL 查询

一旦连接建立,你就可以执行 SQL 查询了。这里有几个例子:

  • 插入数据
const sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com')";
connection.query(sql, (err, result) => {
    if (err) throw err;
    console.log("Record inserted with ID:", result.insertId);
});
  • 查询数据
const sql = "SELECT * FROM users";
connection.query(sql, (err, results) => {
    if (err) throw err;
    console.log(results); // 输出查询结果
});
  • 更新数据
const sql = "UPDATE users SET name = ? WHERE email = ?";
const values = ['Jane Doe', 'john.doe@example.com'];
connection.query(sql, values, (err, result) => {
    if (err) throw err;
    console.log(result.affectedRows + " record(s) updated");
});
  • 删除数据
const sql = "DELETE FROM users WHERE email = ?";
const email = 'john.doe@example.com';
connection.query(sql, [email], (err, result) => {
    if (err) throw err;
    console.log(result.affectedRows + " record(s) deleted");
});

4. 关闭连接

当完成所有数据库操作后,记得关闭数据库连接:

connection.end((err) => {
    if (err) {
        console.log('Error closing the connection:', err);
        return;
    }
    console.log('Database connection closed.');
});

这些是使用 mysql 模块进行基本数据库操作的基本步骤。希望这对你有所帮助!

使用Node.js连接MySQL数据库主要通过mysql模块。首先需要安装该模块:

npm install mysql

然后可以使用以下代码连接到MySQL数据库:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'yourusername',
  password: 'yourpassword',
  database: 'yourdatabase'
});

connection.connect(error => {
  if (error) throw error;
  console.log('Connected!');
});

// 执行查询
connection.query('SELECT * FROM users', (error, results, fields) => {
  if (error) throw error;
  console.log(results);
});

connection.end();

这段代码创建了一个连接,执行了SQL查询,并处理了结果。记得在完成操作后调用end()关闭连接。

回到顶部