介绍

mysql, 关系型数据库。

1. 语法

操作库

  • 创建 CREATE DATABASE test;
  • 删除 DROP DATABASE test;
  • 修改
  • 查询 SHOW DATABASES;
  • 切换 USE test;

操作表

  • 创建
  • 查看 SHOW TABLES;
  • 查看(结构)DESC students;
  • 查看(语句)SHOW CREATE TABLE students;
  • 删除 DROP TABLE students;

操作条目

  • 插入 INSERT INTO
  • 删除 DELETE FROM — WHERE id=—;
  • 修改 UPDATE — SET — WHERE id=—;
  • 查询 SELECT * FROM —;

2. 业务

数据库搭建

DOS模式

  1. EXIT // 退出

安装

参见: https://www.runoob.com/mysql/mysql-install.html

查看

注意, 必须以分号结尾

版本

  1. mysqladmin --version

端口

  1. mysql -u root -p
  2. show global variables like 'port';
  3. +---------------+-------+
  4. | Variable_name | Value |
  5. +---------------+-------+
  6. | port | 3306 |
  7. +---------------+-------+
  8. 1 row in set (0.00 sec)

用户

  1. select user();
  2. +----------------+
  3. | user() |
  4. +----------------+
  5. | root@localhost |
  6. +----------------+
  7. 1 row in set (0.00 sec)

查看数据库

  1. show databases;
  2. +--------------------+
  3. | Database |
  4. +--------------------+
  5. | information_schema |
  6. | book |
  7. | mysql |
  8. | performance_schema |
  9. +--------------------+
  10. 4 rows in set (0.00 sec)

查询数据

  1. use book;
  2. select * from book_list;
  3. +----+-----------+-----------------+------------+-------+
  4. | id | name | author | date | price |
  5. +----+-----------+-----------------+------------+-------+
  6. | 1 | 小王子 | 埃克苏佩里 | 1941-10-01 | 100 |
  7. +----+-----------+-----------------+------------+-------+
  8. 1 row in set (0.00 sec)

命令行操作

连接

连接数据库 mysql -u root -p

创建数据库

  1. CREATE DATABASE BOOK;

创建数据表

  1. CREATE TABLE IF NOT EXISTS `book_list`(
  2. `id` INT UNSIGNED AUTO_INCREMENT,
  3. `name` VARCHAR(100) NOT NULL,
  4. `author` VARCHAR(40) NOT NULL,
  5. `date` DATE,
  6. `price` FLOAT,
  7. PRIMARY KEY ( `id` )
  8. )ENGINE=InnoDB DEFAULT CHARSET=utf8;

插入数据

  1. INSERT INTO book_list ( name, author, date, price)
  2. VALUES
  3. ( '小王子', '埃克苏佩里', '1941-10-1', 100 );

nodejs操作数据库

nodejs 连接

  1. var mysql = require('mysql')
  2. var co = mysql.createConnection({
  3. host: '119.45.34.210',
  4. user: 'root',
  5. password: '123456',
  6. port: '3306',
  7. database: 'book'
  8. })
  9. co.connect();
  10. co.query('SELECT * FROM book_list', (err, result, filelds) => {
  11. // console.log(err, result, filelds)
  12. if (err) throw err
  13. console.log('book_list:', result.length, result)
  14. });
  15. co.end((err) => {
  16. if (err) throw err;
  17. console.log('[connenct end] succeed!')
  18. });

增删改查

  1. const addSql = `INSERT INTO book_list ( name, author, date, price)
  2. VALUES
  3. ( ?, ?, ?, ? );`;
  4. const addSqlParams = ['钢铁是怎样练成的', '高尔基', '1989-10-23', 65];
  5. co.query(addSql, addSqlParams, (err, result, filelds) => {});
  6. const updateSql = 'UPDATE book_list SET price = ? where id = ?';
  7. const updateSqlParams = [25, 2];