目錄
在專案中操作MySQL資料庫的步驟
執行資料庫的操作
查詢資料
插入資料
修改資料
洗掉資料
在專案中操作MySQL資料庫的步驟

1、安裝操作MySQL資料庫的第三方模塊(mysql)
mysql 模塊是托管于 npm 上的第三方模塊,它提供了在 Node.js 專案中連接和操作 MySQL 資料庫的能力, 想要在專案中使用它,需要先運行如下命令,將 mysql 安裝為專案的依賴包: npm install mysql
2、通過mysql模塊連接到MySQL資料庫
配置mysql模塊
//引入mysql2模塊
const mysql = require('mysql2');
//2、創建資料庫的連接
const connection = mysql.createConnection({
host:'localhost', //資料庫服務器地址
port:3306, //mysql資料庫的埠號
user:'root', //連接mysql的用戶名
password:'******', //連接mysql的密碼
database:'dbms' //要連接的資料庫
})
3、通過mysql模塊執行SQL陳述句
執行資料庫的操作
在我的資料庫dbms中存在一張student表為:

查詢資料
A、普通查詢:query(sql,回呼函式)
B、條件查詢:query(sqlString,values,回呼函式),引數values對應的是sqlString中的占位符
示例:查詢student表中cno為3的學生資訊(?表示占位符)
//查詢資料庫中的表格的資料,回呼函式中err引數存放的是查詢錯誤的資訊,若查詢成功則result引數中放的是查詢的結果集
//條件查詢
connection.query({
sql:'select * from student where cno = ?',
values:['3']
},(err,result)=>{
if(err){
console.log(err);
return;
}
console.log(result);
})
//普通查詢
connection.query('select * from indent',(err,result)=>{
if(err){
console.log(err);
return;
}
console.log(result);
})
條件查詢的結果為:

插入資料
Insert into 表名(列名…) values(值…)
示例:向表student中插入一行資料
var addsql = "insert into stu(sno,cno,sname,sgender,sage,saddress) values(?,?,?,?,?,?)";
var addsql_params = ['12','3','劉備','男','29','陜西'];
connection.query({
sql:addsql,
values:addsql_params
},(err,result)=>{
if(err){
console.log(err);
return;
}
console.log('插入結果為:'+result);
})
插入后的結果為:

修改資料
Update 表名 set 列名=值,… where 條件
注意:不加where條件就會把所有的資料都更新
示例:將剛才添加的資料中姓名修改為‘巴啦啦小魔仙’,年齡修改為27
var updatesql = "update student set sname=?,sage=? where sno=?";
var updatesql_params = ['巴啦啦小魔仙',27,'12'];
connection.query({
sql:updatesql,
values:updatesql_params
},(err,result)=>{
console.log("受影響的行數:"+result.affectedRows);
console.log("改變的行數:"+result.changedRows);
})
修改后的結果:

洗掉資料
Delete from 表名 [where 條件]
示例:洗掉剛才添加的sno為12的學生資訊
var delsql = "delete from student where sno=?";
connection.query(delsql,'12',(err,result)=>{
if(err){
console.log(err);
return;
}
console.log("洗掉的行數:"+result.affectedRows);
})
洗掉后的結果:

注意:防止sql的注入式攻擊的方法:
注入式攻擊:在進行陳述句的增刪改查等操作時若有人攔截并添加一條永遠滿足的陳述句則會查詢出所有的資料資訊
select from stu where Sid=’S_1001’ (注入式攻擊如在后面加or 1=1)
(1)使用占位符:?(提前預編譯)
(2)使用connection.escape([引數欄位])對值進行轉義
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/327919.html
標籤:其他
