目錄
一 . mysql的基本使用
1. 安裝與引入
1. 1 首先要安裝包
npm install -s mysql
1.2 引入包
const mysql = require('mysql');
2. 介紹
這是mysql的node.js驅動程序。它是用JavaScript編寫的,不需要編譯,並且100%獲得MIT許可。
這是有關如何使用它的示例:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
在此示例中,我們瞭解到:
- 在連接上調用的每個方法都按順序排隊並執行。
- 關閉連接是通過使用
end()
該連接來確保在將退出數據包發送到mysql服務器之前執行所有剩餘查詢的。
3. 建立連接
3.1基本使用:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
常用連接選項:
host
:您要連接的數據庫的主機名。(默認值:localhost
)port
:要連接的端口號。(默認值:3306
)user
:要作爲身份驗證的MySQL用戶。password
:該MySQL用戶的密碼。database
:用於此連接的數據庫名稱(可選)。
3.2 池連接
創建一個池並直接使用它:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
這是pool.getConnection()
-> connection.query()
-> connection.release()
代碼流的快捷方式。使用pool.getConnection()
有助於共享連接狀態以用於後續查詢。這是因爲對的兩次調用 pool.query()
可能使用兩個不同的連接並並行運行。這是基本結構:
var mysql = require('mysql');
var pool = mysql.createPool(...);
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
// Use the connection
connection.query('SELECT something FROM sometable', function (error, results, fields) {
// When done with the connection, release it.
connection.release();
// Handle error after the release.
if (error) throw error;
// Don't use the connection here, it has been returned to the pool.
});
});
如果要關閉連接並將其從池中刪除,請 connection.destroy()
改用。下次需要該池時,該池將創建一個新連接。
連接是由池延遲創建的。如果將池配置爲最多允許100個連接,但僅同時使用5個,則僅建立5個連接。連接也以循環方式循環,連接從池的頂部開始並返回到底部。
從池中檢索到先前的連接時,會將ping數據包發送到服務器,以檢查連接是否仍然良好。
二. mysql常用指令
1. 查詢數據(select)
基本select語句: 一個基本的select語句可分解成三個部分:查找什麼數據(select)、從哪裏查找(from)、查找的條件是什麼(where)。
1.1 基本語法
- select <目標列表達式列表>
- [into 新表名]
- from 表名或視圖名
- [where <條件>]
- [group by <分組表達式>]
- [having <條件>]
- [order by <排序表達式>[ASC|DESC]]
1.2 查詢指定字段
1. 查詢表中所有列
在select語句指定列的位置上使用*號時,表示查詢表的所有列。
模板:select * from tb_name;
select * from student
案例:
const express = require('express');
//引入mysql
const mysql = require('mysql');
const app = express();
//處理post請求的參數
app.use(express.urlencoded());
app.use(express.json());
// Create a pool and use it direct
const pool = mysql.createPool({
connectionLimit:10, //連接池的數量
host:'localhost', //訪問的地址
user:'root',
password:'root',
database:'students'
})
//RESTfu路由風格
app.get('/students',(req,res) => {
// res.send('獲取學生信息');
pool.getConnection(function(err, connection) {
//有錯誤就拋出錯誤
if (err) throw err;
console.log('數據庫連接成功');
// 沒有錯誤即說明說數據庫連接成功,就可以對數據庫進行操作了
connection.query('SELECT * FROM student', function (error, results, fields) {
if (error) throw error;
//1. 查詢數據結果
res.json(results);
});
});
})
app.listen(3000,()=> {
console.log('server start at 3000 port');
})
2. 查詢表中指定的列
查詢多列時,列名之間要用逗號隔開。
模板: select <字符型字段>,<字符型字段> ... from tb_name;
//從學生表中選擇name和age兩列
SELECT name,age FROM student
3. 指定查詢結果中的列標題
通過指定列標題(也叫列別名)可使輸出結果更容易被人理解。
模板:select <字段> as 別名,<字段2> as 別名2 from bt_name;
//查詢結果中使用student代替name
SELECT name as studentname,age FROM student
1.3 查詢指定的行
用where子句實現條件查詢
通過where子句實現,該子句必須緊跟在From子句之後。 格式爲:select * from 表名 where <條件>;
說明:在查詢條件中可使用以下運算符或表達式:
- 運算符 運算符標識 比較運算符 <=,<,=,>,>=,!=,<>,!>,!<
- 範圍運算符 between... and,not between... and
- 列舉運算符 in,not in
- 模糊匹配運算符 like,not like
- 空值運算符 is null,is not null
- 邏輯運算符 and,or,not
1. 使用比較運算
模板:select * from tb_name where <字段> >= n ;
//查詢年齡大於20的數據
SELECT * FROM student where age > 20
2. 指定範圍
用於指定範圍的關鍵字有兩個:between...and和 not between...and。
格式爲:select * from tb_name where <字段> [not] between <表達式1> and <表達式2>;
- between關鍵字之後的是範圍的下限(即低值)
- and關鍵字之後的是範圍的上限(即高值) 用於查找字段值在(或不在)指定範圍的行
SELECT * FROM student where age between 13 and 24
// 查詢age字段的值 在13到24 範圍的數據
SELECT * FROM student where age node between 13 and 24
// 查詢age字段的值 不在13到24 範圍的數據
3. 使用枚舉:
使用in關鍵字可以指定一個值的集合,集合中列出所有可能的值,當表達式的值與集合中的任一元素個匹配時,即返回true,否則返回false。
模板:select * from tb_name where <字段> [not] in (值1,值2,...,值n);
SELECT * FROM student where age in (17,21)
// 查詢age字段的值 是23 或者43 的數據
SELECT * FROM student where age not in (18,21)
// 查詢age字段的值 不是23 或者43 的數據
4. 使用通配符進行模糊查詢:
可用like 子句進行字符串的模糊匹配查詢,like子句將返回邏輯值(true或False)。
模板: select * from tb_name where <字段> [not] like <匹配串>;
其含義是:
查找指定字段值與匹配串相匹配的記錄。匹配串中通常含有通配符%。 其中: %:代表任意長度(包括0)的字符串
//查詢姓名中有歡的數據
SELECT * FROM student where name like "%歡%"
5. 使用null的查詢
當需要判定一個表達式的值是否爲空值時,使用 is null關鍵字。 當不使用not時,若表達式的值爲空值,則返回true,否則返回false;當使用not時,結果剛好相反。
模板:select * from tb_name where <字段> is [not] null;
SELECT * FROM student where name is null
// 查詢username字段爲空的數據
SELECT * FROM student where name is not null
// 查詢username字段不爲空的數據
6. 多重條件查詢:
使用邏輯運算符 邏輯運算符and(與:兩個條件都要滿足)和or(或:滿足其中一個條件即可)可用來聯接多個查詢條件。and的優先級高於or,但若使用括號可以改變優先級。
模板:select * from tb_name where <字段> = 'values' and <字段> > n;
SELECT * FROM student where username like "%歡%" and sex = "女"
// 查詢username 字段值包含"歡" 並且 sex字段值爲"女"
SELECT * FROM student where username like "%歡%" or age >= 20
// 查詢username 字段值包含"歡" 或者 age字段 大於等於 20
1.4 對查詢結果排序
order by子句可用於對查詢結果按照一個或多個字段的值(或表達式的值)進行升序(ASC)或降序(DESC)排列,默認爲升序。 格式:order by {排序表達式[ASC|DESC]}[,...n]; 其中:排序表達式既可以是單個的一個字段,也可以是由字段、函數、常量等組成的表達式,或一個正整數。
模板:select * from tb_name order by <排序表達式> <排序方法>;
//// 將查詢的結果按照id 字段的降序排序
SELECT * FROM student where age > 18 order by id DESC
2. 插入數據(insert)
insert into 語句用於向表格中插入新的行:
第二種形式需要指定列名及被插入的值: 模板:insert into tb_name (column1,column2,column3,...) values (value1,value2,value3,...);
INSERT INTO student (username,age,sex,classname) VALUES ("張三",12,"男",[1,3])
插入數據案例:
app.post('/students',(req,res) => {
// res.send('新增學生信息');
console.log(req.body);
let {name,id,birth,age,sex} = req.body;
birth = birth && new Date(birth).getTime();
// console.log(name,id,sex,birth,age);
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
connection.query('INSERT INTO student (name,age,sex,birth,id) values (?,?,?,?,?)',[name,age,sex,birth,id] ,function (error, results, fields) {
if (error) throw error;
res.send('數據插入成功');
});
});
})
3. 修改數據(update)
Update 語句用於修改表中的數據。
模板: update tb_name set 列名稱 = 新值 where 列名稱 = 某值;
UPDATE student SET name = 張三 WHERR id = 003
案例:
app.put('/students/:id',(req,res) => {
// res.send('修改學生信息');
let {id} = req.params;
console.log(id)
let student = req.body
console.log(student)
let data = []
for(let key in student){
data.push(key,student[key])
}
data.push(id)
console.log(data)
// res.send("更新學生信息")
pool.getConnection(function(err, connection) {
// 有報錯就拋出報錯
if (err) throw err; // not connected!
// 更新數據
connection.query(`UPDATE student SET ?? = ? WHERE id = ?`,data, function (error, results, fields) {
// 查詢數據庫有錯誤就拋出錯誤
// console.log(error)
if (error) throw error;
res.send("數據更新成功")
});
});
})
4. 刪除數據
4.1 刪除單行數據
delete from tb_name where 列名稱 = 某值;
delete from student where id = 1
4.2 刪除所有數據
可以在不刪除表的情況下刪除所有的行。這意味着表的結構、屬性和索引都是完整的.
delete * from tb_name 或 delete * from tb_nametb_name;
案例:
app.delete('/students',(req,res) => {
// res.send('刪除學生信息');
pool.getConnection(function(err, connection) {
if (err) throw err; // not connected!
connection.query('delete from student where id = 5', function (error, results, fields) {
if (error) throw error;
res.send('數據刪除成功')
});
});
})