終於有一天,本身開始主動寫demo和總結。 來看看怎麼用強大的Nodejs來操做數據庫吧。node
安裝mysql的過程就不說啦,直接看個人數據庫結構吧mysql
1.鏈接數據庫sql
//connect.js
const mysql = require("mysql");
const connection = mysql.createConnection({
host: "localhost", //主機地址
user: "root", //數據庫用戶名
password: "123456", //數據庫用戶密碼
database: "test" //數據庫名
});
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);
}); //檢驗鏈接成功
複製代碼
執行 node connect.js 出現The solution is: 2
表示鏈接成功數據庫
2.增長用戶 先鏈接數據庫再定義增長用戶的模板bash
//userInsert.js
const mysql = require("mysql");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
database: "test"
});
connection.connect();
//鏈接以後進行插入操做
const addSql = 'insert user (id,name,sex,age,tel,mail,note) values(?,?,?,?,?,?,?)';
const addSqlParams = [null,"孫","man",13,"1234567","234567@qq.com","fghavi"];
connection.query(addSql,addSqlParams,function (err,result) {
if(err){
console.log('[INSERT ERROR] - ',err.message);
return;
}
console.log('INSERT ID:',result);
});
connection.end();
複製代碼
執行node userInsert.jsui
3.查詢操做 查詢操做也要先連接數據庫再對數據庫進行操做spa
const mysql = require("mysql");
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
database: "test"
});
connection.connect();
//鏈接以後進行查詢操做
const sql = "select * from user"; //選擇全部
connection.query(sql,function (err, result) {
if(err){
console.log('[SELECT ERROR] - ',err.message);
return;
}
console.log(result);
}); //輸出查詢結果
connection.end();
複製代碼
4.更新操做 根據數據庫的主鍵進行查詢更新code
//userUpdate.js
//鏈接數據庫與以前的相同 鏈接以後進行修改
const modSql = "update user set name=?,sex=?,age=?,tel=?,mail=?,note=? where id = ?";
//根據id進行修改
const modSqlParams = ["及","woman",32,"345678","ndsajvn@qq.com","adsvfadsv",2];
//修改後的內容
connection.query(modSql,modSqlParams,function (err, result) {
if(err){
console.log('[UPDATE ERROR] - ',err.message);
return;
}
console.log('UPDATE success',result.affectedRows);
});
//輸出更新是否成功
connection.end();
複製代碼
能夠再對數據庫進行查詢判斷是否更新成功
5.數據庫刪除 根據數據庫主鍵對某一條記錄進行刪除操做cdn
//userDelete.js
//l數據庫鏈接以後進行刪除操做
const delSql = 'delete from user where id = "4"';
//根據id刪除
connection.query(delSql,function (err, result) {
if(err){
console.log('[DELETE ERROR] - ',err.message);
return;
}
console.log('DELETE success',result.affectedRows);
});
connection.end();
複製代碼
執行node userDelete.js 能夠看到刪除結果,也能夠經過數據庫查詢再判斷是否刪除成功。blog
6.遇到的問題
就這麼多啦~