Node.js操作Mysql的简单示例

API的封装:封装为系统可用的工具,分为线上和线上的数据库。
使用:让API直接操作数据库,不再使用假数据。

DEMO代码:

const mysql = require('mysql');

// 创建数据库连接
const con = mysql.createConnection({
  // 主机名/端口/数据库/用户名/密码
  host: 'localhost',
  port: '3306',
  database: 'myblog',
  user: 'root',
  password: '113647'
});

// 开始连接
con.connect();

// sql语句
// 查询:返回查询结果
const sql = 'select id,username from users';
// 更新:返回结果中看affectedRows和changedRows字段
// const sql = 'select id,username from users';
// 插入:返回结果中看insertedId字段

// 执行sql语句
con.query(sql, (err, result) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(result);
});

// 关闭连接,否则结束不了该进程
con.end();

猜你喜欢

转载自www.cnblogs.com/wljqds/p/11579007.html