1. 创建项目,安装mysql
创建项目文件夹test,
在test文件夹下yarn add mysql --save
安装mysql;
2. node使用mysql
在test文件夹下,创建test.js文件,内容如下:
const mysql = require("mysql"); //引入mysql
// 创建链接对象
const con = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "123456",
port: "3306",
database: "testschema"
})
// 开始链接
con.connect()
// 执行sql语句
const sql = "select * from usesrs;"
con.query(sql, (err, result) => {
if (err) {
console.log(err)
return
}
console.log("获取结果成功:" + result)
})
// 关闭链接
con.end()
这里列举一些基本的增删改查语句:
/**
* 增
* insert into users (username, `password`, realname) values ("zhangsan", "123","张三");
*/
/**
* 删
* delete from users where username="lisi";
*/
/**
* 改
* update users set realname="李四2" where username="lisi";
*/
/**
* 查
* select * from users; 查询所有列
* select id,username from users; 查询部分列
* select * from users where username="zhangsan" and `password`="123"; 多个条件查询
* select * from users where username like "%zhang%"; 模糊查询
* select * from users where `password` like "%123%" order by id desc; 排序
*/