这是我参与更文挑战的第10天,活动详情查看:更文挑战
今天开始学习数据库操作,然后把之前的假数据都从数据库拿取。
MySQL安装
官网地址:dev.mysql.com/downloads/i…
MySQL的具体安装可以参考: zhuanlan.zhihu.com/p/37152572
然后安装 MySQL Workbench
官网地址: dev.mysql.com/downloads/w…
安装好 workbench
后,点击+
,连接数据库
OK,到这一步安装MySQL数据库成功~
SQL命令
下面简单写一下用到的
sql
命令,实现增删改查
use myblog;
-- show tables;
-- 插入
insert into users (username,`password`,realname) values ('emier','666', '天魁星');
-- 查询
select * from users;
-- 查询部分字段数据
select id, username from users;
-- 查询符合条件的数据
select * from users where username='emier' and `password`='666';
select * from users where username='emier' or `password`='666';
-- 模糊查询(like: 但凡存在)
select * from users where username like '%mier%';
-- 排序
select * from users where username like '%mier%' order by id;
-- 倒序
select * from users where username like '%mier%' order by id desc;
-- 更新
-- update 表名 set 字段名='xxx' where条件
update users set realname='itmier' where username='emier';
-- 解决问题: Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
SET SQL_SAFE_UPDATES=0;
-- 删除
delete from users where username='emier';
-- 一般不删除,只是更新状态
update users set state='0' where username='emier'; -- 软删除
select * from users where state='1';
-- 不等于
select * from users where state <> '0';
-- 插入数据
insert into blogs (title, content, createtime, author) values ('震惊!标题D', '我是内容,内容为王DD', 1623336080690, 'tmier');
select * from blogs;
select * from blogs order by createtime desc;
select * from blogs where author='tmier' order by createtime desc;
select * from blogs where title like '%标题D%' order by createtime desc;
-- 查询版本
select version()
NodeJS操作SQL初探
index.js
npm i mysql
const mysql = require('mysql')
// 创建链接对象
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '你看不见...',
port: '3306',
database: 'myblog'
})
// 开始连接
con.connect()
// 执行sql语句
const sql = 'select * from users;'
// const sql = 'select id, username from users;'
// const sql = `update users set realname='哈哈' where username='emier';`
// const sql = `insert into users (username,${'password'},realname) values ('emier2','666', '天魁星');`
// const sql = `insert into blogs (title, content, createtime, author) values ('震惊!标题E', '我是内容,内容为王EE', 1623336080690, 'tmier');`
con.query(sql,(err,result) => {
if(err){
console.error(err)
return
}
console.log(result);
})
// 关闭连接
con.end()
今天安装好了MySQL,比较意外的顺利,因为我记得上大学的时候学习数据库,安装MySQL因为环境问题遇到的问题太多了,没想到这次非常顺利就安装成功了~
然后就是今天简单的使用了下sql的增删改查的几行命令, 虽然好久没使用,但敲了几次代码,感觉也不陌生了~
今天也是第一次使用Node操作MySQL, 意外的简单~ 等在学习下继续更新~