1. 建库
create DATABASE if not exists dev1 default charset utf8mb4 collate utf8mb4_bin; # 不存在创建,默认utf8mb4字符能存储emoji
drop database dev1; # 删除
2. 建表
create table if not exists tb1 (
id INT not null primary key auto_increment,
name VARCHAR(25),
age INT not null
); # 自增主键 不为空
3. 建视图
create VIEW v1 as select * from tb1;
drop view v1;
4. 表操作
4.1 插入insert
插入多条数据2种方式
insert into tb(name, age) values('张三',20), ('张三',20)
insert into ... on duplicate key update; # 唯一索引(包括主键索引)的冲突,即这个唯一值重复了,则不会执行insert操作,而执行后面的update操作
node示例
var mysql = require('mysql')
var connection = mysql.createConnection({
host: '*******',
user: '****',
password: '***',
database: 'dev1',
multipleStatements: false, // 执行多条 mysql.format()
})
connection.connect()
connection.query('insert into tb1(name, age) values (?,?)',[`菜鸟的编号`,18], (e, res, fields)=>()) // 插入1条
connection.query('insert into tb1(name, age) values ?',[[`菜鸟的编号`,18], [`菜鸟的编号1`,18]], (e, res, fields)=>()) // 插入多条
connection.end(e=>()) // 执行结束回调
4.2 查询
select distinct name from tb1;
update tb1 set name='xx' where id=200