node实现mysql数据连接

准备工作:

  1. 项目文件夹下创建index.js
  2. npm init -y
  3. 安装mysql依赖:npm install mysql

开始写代码:

index.js文件中

// 引入mysql依赖
const mysql = require('mysql')

// 创建连接配置
const con = mysql.createConnection({
    // 服务端地址
    host: 'localhost',
    // 连接端口
    port: '3306',
    // 数据库账号
    user: 'root',
    // 数据库密码
    password: 'root',
    // 指定数据库
    database: '你要连接的数据库'    
})

// 开始连接
con.connect()

// 发送sql
const sql = `select * from 表`
con.query(sql, (err, result) => {
    if (err) {
        console.log(err)
        return
    }
    console.log(result)
})

//关闭连接
con.end()
  • 上面代码数据库配置换成你自己的,直接拉走
  • node index.js直接就打印出数据库内容
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章