node 中数据库连接的三种方式(mysql案例)

mysql包的数据库连接首先安装

npm i mysql

const mysql = require("mysql2");
/*建立数据库链接  连接配置 */
// createPool
//getConnection
// createPool 连接池    --- getConnection  获取到连接对象 操作后建议主动的释放连接
// createConnection方法创建连接对象   -- connect  
// 使用createConnection方法创建一个表示与mysql数据库服务器之间连接的connection对象

var conn = mysql.createConnection({
  host:'127.0.0.1',
  user: 'root',
  password: 'root',  // 修改为你的密码
  port: '3306',
  database: 'ruanmoutest'  // 请确保数据库存在
});

 // 连接
 conn.connect((err) => {
  if(err) {
      throw(err);
  }
  console.log('数据库连接成功!')
})


// 查询 conn.query() 执行sql语句      --- mysql  
//  conn.execute   执行sql语句   conn.query()   -mysql2
// 创建表
const CREATE_SQL = `CREATE TABLE IF NOT EXISTS test (
    id INT NOT NULL AUTO_INCREMENT,
    username VARCHAR(45) NULL,
    age INT NULL,
    message VARCHAR(45) NULL,
    PRIMARY KEY (id))`;
const INSERT_SQL = `INSERT INTO test(username,age,message) VALUES(?,?,?)`;  // 使用占位符
const SELECT_SQL = `SELECT * FROM test`;
// conn.query(CREATE_SQL, (err, data) => {
//     if (err) {
//         throw err;
//     }
//     // 插入数据
    
//     // conn.query(`INSERT INTO test(username,age) VALUES('mk',20)`, (err, result) => {
//     conn.query(INSERT_SQL, ['song','10',"hello,world"], (err, result) => {
//         if (err) {
//         throw err;
//     }
   
//     conn.query(SELECT_SQL, (err, results) => {
//         console.log(JSON.stringify(results));
//         conn.end(); // 若query语句有嵌套,则end需在此执行
//     })
//     });
// });

conn.query(`INSERT INTO test(username,age) VALUES('test3',20)`);

mysql2包的数据库连接首先安装

npm i mysql2

(async () => {
    // mysql2 是mysql的一个扩展
    const mysql = require('mysql2/promise')

    // 连接配置
    const cfg = {
        host:'127.0.0.1',
        user: 'root',
        password: 'root',  // 修改为你的密码
        port: '3306',
        database: 'ruanmoutest'  // 请确保数据库存在
    }

    const connection = await mysql.createConnection(cfg)

    let ret = await connection.execute(`
        CREATE TABLE IF NOT EXISTS test (
            id INT NOT NULL AUTO_INCREMENT,
            message VARCHAR(45) NULL,
        PRIMARY KEY (id))
    `)
    console.log('create', ret)

    ret = await connection.execute(`
            INSERT INTO test(message)
            VALUES(?)
    `, ['ABC'])
    console.log('insert:', ret)


    ret = await connection.execute(`
            SELECT * FROM test
    `)
    console.log(JSON.stringify(ret[0]))
    // console.log(ret[1])

    connection.end()

})()    

ORM框架sequelize的使用

(async () => {
    const Sequelize = require("sequelize");

    // 建立连接
    const sequelize = new Sequelize("ruanmoutest", "root", "root", {
        host: "localhost",
        dialect: "mysql",
        operatorsAliases: false
    });

    // 定义模型,建表
    const Fruit = sequelize.define("Fruit", {
        name: {
            type: Sequelize.STRING(20),
            allowNull: false
        },
        price: {
            type: Sequelize.FLOAT,
            allowNull: false
        }
    },
        {
            timestamps: false
        });

    // Fruit.prototype.totalPrice = function (count) {
    //     return (this.price * count).toFixed(2);
    // };
    // 同步数据库,force: true则会删除已存在的表
    let ret = await Fruit.sync({ force: false })

    // ret = await Fruit.create({
    //     name: "香蕉",
    //     price: 3.5
    // })

    // ret = await Fruit.create({
    //     name: "西瓜",
    //     price: 20
    // })

    ret2 = await Fruit.findAll()
    console.log(ret2);


    // 使用实例方法
    // Fruit.findAll().then(fruits => {
    //     const [f1] = fruits;
       
    //     fruits.forEach((option,index)=>{
    //         console.log(option);
    //     })
    //     console.log(`买5kg${f1.name}需要¥${f1.totalPrice(5)}`);      
    // });

    //找出某一个水果
    // Fruit.findOne({ where: { name: "香蕉" } }).then(fruit => {
    //     // fruit是首个匹配项,若没有则为null
    //     console.log(fruit.get());
    // });

    // console.log('findAll', ret.amount, JSON.stringify(ret))


})();

原创文章 207 获赞 173 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/105889431