node中的mysql模块

# 如果前面没有安装过其他模块,需要先初始化
npm i mysql

 一。在Node中使用MySQL模块一共需要5个步骤:

// 1. 加载mysql模块
const mysql = require('mysql');
// 2. 创建连接对象(设置连接参数)
const conn = mysql.createConnection({
    // 属性:值
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '',
    database: 'yingxiong'
});

// 3. 连接到MySQL服务器
conn.connect();
// 4. 完成查询(增删改查)(执行sql语句)
/*
conn.query(SQL语句, [SQL中占位符的值], (err, result, fields) => {
    err: 错误信息
    result: 查询结果
    fields: 当前查询过程中涉及到的字段信息,一般用不着
});
*/
// 5. 关闭连接,释放资源
conn.end();

 二。查询 

执行查询类型的SQL语句,查询结果(result)是一个数组,每个单元是对象,对象的属性是数据表的字段名

conn.query('select * from heroes limit 2', (err, result) => {
     if (err) throw err;
     console.log(result);
});

  

猜你喜欢

转载自www.cnblogs.com/star-meteor/p/12757417.html
今日推荐