NodeJS

连接MySQL数据库

MySQL

代码示例:

// index.js

const express = require('express')
const app = express()
const mysql2 = require('mysql2')

function getDBConfig() {
    return {
        host: '127.0.0.1',
        port: 3306,
        user: 'root',
        password: '123',
        database: 'mysqldb',
        connectionLimit: 1
    }
}

app.get('/', async (req, res) => {
    const config = getDBConfig()
    const promisePool = mysql2.createPool(config).promise()
    const name = "HQSY"
    // const users = await promisePool.query('select * from students')
    // const users = await promisePool.query(`select * from students where name="${name}"`)
    const users = await promisePool.query(`select * from students where name=?`, [name])
    console.log(users[0])
    res.send({
        ok: 1,
        data: users[0]
    })
})

app.listen(3000)