一,mysql数据库中的增删改查 where 值(为1时田间为true/0时为false)
1.查询
语法:select 字段 from where 条件
获取id=2的一条数据中的name
select `name` from 表名 where id=2
//获取id等于2的name值
模糊查询 /查询name中带 n的数据(模糊查询)
select * from comment where name like '%n%'
查询整个表
select * from comment where 1
2.删除
delete from `表名` where 条件
删除id等于4的数据
DELETE FROM `comment` where id=4
3.修改
UPDATE 表名 set 字段名='值' where 条件
将id=7的数据 name的值(更新为/修改为)"前端"
UPDATE `comment` set name='前端' where id=7
4.增加
INSERT INTO 表名 (字段1,字段2) values (字段1数据,字段2数据)
INSERT INTO `comment` (name,msg) values("小5","小五");
//代表添加一行数据
INSERT INTO `comment` (name,msg) values("小白","15"),("小6","吃饭")
//同时添加多条数据
二,nodejs的使用及步骤
分为3步
1初始化项目
npm init -y
//项目初始化
2.安装mysql包(插件)
npm i mysql
三,再nodejs中链接mysql数据库
分为6步
1. 导入mysql
const mysql = require("mysql")
2. 创建连接
const conn = mysql.createConnect({
host:"localhost",
user:"root",
password:"123456",
database:"feedback"
})
//host域名,user用户名,password密码,database数据库名
3. 连接数据库
conn.connect((err)=>{
if(!err){console.log("连接数据库成功!")}
else{console.error("连接失败",err) }
})
4 定义sql
const sql = "select * from comment where 1";
5 执行sql数据库
conn.query(sql,function(err,data){
if(err){
// 打印错误
console.error("错误",err)
}else{
// 把获取到的数据打印
console.log(data)
}
})
6 关闭sql
conn.end(function(err){
if(!err){console.log("数据库连接关闭")}
else{console.error(err)}
})
四 http开启服务器
一共分为3步
1.导入http
const http = require("http")
2.创建服务器
const server = http.createServer((req,res)=>{
res.statusCode = 200;
res.setHeader("Content-Type","application/json;charset=utf-8")
res.end('{"statusCode":0,"msg":"成功"}')
})
3 监听端口
server.listen(8080,()=>{console.log("服务器启动成功 http://localhost:8080")})
五.expess 更好用的nodejs服务器框架
1 安装框架
npm i express
2.创建app
const express = require("express")
const app = express()
3.监听路由
app.get("/",function(req,res){
res.send("<h1>首页内容</h1>")
})
app.post("/",function(req,res){
res.send("<h1>post返回首页内容</h1>")
})
app.get("/about",function(req,res){
res.send("<h1>关于页面</h1>")
})
4监听端口
app.listen(8888,function(){
console.log("服务器启动成功 http://localhost:8888")
})
express 使用静态文件夹
通常是public 在public内容可以在浏览器里面自动访问
public要和当前文件放在同一目录
浏览器访问public目录相当于 /
app.use(express.static('public'))