简单使用MySQL

安装 MySQL库

npm i -S mysql

配置

新建db目录,内含index.js 和 config.js

// config.js
module.exports={
    host:'localhost', // 主机名
    user:'root', // 连接数据库的用户名
    password:'root', // 密码
    database:'book' // 表
}
基本使用

连接 - 增删改查 - 释放连接

const mysql=require('mysql')
const {host,user,password,database}=require('./config')

function connect(){
    return mysql.createConnection({
        host,
        user,
        password,
        database,
        multipleStatements:true
        //multipleStatements:允许每条 mysql 语句有多条查询.
        //使用它时要非常注意,因为它很容易引起 sql 注入(默认:false)
    })
}

function querySql(sql) {
    const conn = connect()
    return new Promise((resolve, reject) => {
        try {
            conn.query(sql, (err, results) => {
                if (err) {
                  
                } else {
                    resolve(results)
                }
            })
        } catch (e) {
            reject(e)
        } finally {
            conn.end() //调用conn.end()释放连接
        }
    })
}

module.exports={querySql}


  • 字段最好加上反引号,避免和某些固定的关键字冲突,比如form等
INSERT INTO `表名` (`key1`,`key2`) VALUES ('value1','value2')
delete from book where fileName='xxxxx'
UPDATE book SET author='xxx' WHERE fileName='xxxxx'
UPDATE book SET author='xxx',language='en' WHERE fileName='xxxxx'
select * from contents where fileName='xxxxxxxx' order by `order`

//详细查询 key = value,模糊查询 key like value ,value加上通配符 %
select * from book where `category`='99' and `author` like '%Nylund%' limit 20 offset 0

//返回表student的第10、11、12、13行
select * from student limit 9,4
select * from student limit 4 offset 9

//排序 order by
select * from book order by `id` asc limit 20 offset 0
select * from book order by `id` desc limit 20 offset 0

你可能感兴趣的:(简单使用MySQL)