Node操作MySQL数据库示例代码分享

2025-01-15 04:28:05   小编

在后端开发中,Node与MySQL数据库的结合使用十分广泛。本文将分享Node操作MySQL数据库的示例代码,帮助大家快速上手。

确保你已经安装了MySQL模块。在项目目录下,通过命令行运行 npm install mysql 即可完成安装。

连接数据库是操作的第一步。以下是连接MySQL数据库的示例代码:

const mysql = require('mysql');

// 创建连接池
const pool = mysql.createPool({
  host     : 'localhost',
  user     : 'root',
  password : 'yourpassword',
  database : 'yourdatabase'
});

// 从连接池获取连接
pool.getConnection((err, connection) => {
  if (err) throw err;
  console.log('Connected to MySQL database!');
  connection.release();
});

在上述代码中,我们首先引入了mysql模块,接着创建了一个连接池对象,配置了数据库的主机、用户名、密码和数据库名。通过 getConnection 方法从连接池获取连接,并在连接成功时打印出提示信息,最后释放连接。

接下来,进行数据查询操作。假设我们有一个名为 users 的表,想要查询所有用户数据,代码如下:

pool.getConnection((err, connection) => {
  if (err) throw err;
  const sql = 'SELECT * FROM users';
  connection.query(sql, (error, results, fields) => {
    if (error) throw error;
    console.log(results);
  });
  connection.release();
});

这里通过 query 方法执行SQL查询语句,查询结果会在回调函数的 results 参数中返回,我们简单地将结果打印出来。

插入数据操作也很常见。例如,向 users 表插入一条新记录:

pool.getConnection((err, connection) => {
  if (err) throw err;
  const sql = 'INSERT INTO users (name, email) VALUES (?,?)';
  const values = ['John Doe', 'johndoe@example.com'];
  connection.query(sql, values, (error, results, fields) => {
    if (error) throw error;
    console.log('Data inserted successfully!');
  });
  connection.release();
});

在插入操作中,使用 ? 作为占位符,将实际值放在 values 数组中,这样可以有效防止SQL注入。

Node操作MySQL数据库并不复杂,通过合理使用连接池和各种SQL操作语句,能够轻松实现数据的查询、插入、更新和删除等功能。掌握这些基础代码示例,能为后续的项目开发打下坚实的基础。

TAGS: 示例代码 数据库操作 MySQL数据库 Node操作MySQL

欢迎使用万千站长工具!

Welcome to www.zzTool.com