//下載相關的文件
npm init -y
npm install mysql --save
npm install express --save
npm install body-parser --save
/*
數(shù)據(jù)庫基本操作步驟
*/
const mysql = require('mysql');
// 創(chuàng)建數(shù)據(jù)庫連接
let connection = mysql.createConnection({
host: 'localhost', //數(shù)據(jù)庫所在的服務器域名或者IP
user: 'root', //用戶名
password: '', //密碼
database: 'book' //數(shù)據(jù)庫名稱
});
// 執(zhí)行連接動作
connection.connect();
// 執(zhí)行數(shù)據(jù)庫操作
let sql = 'select * from user';
connection.query(sql, (err, rows, fields) => {
if (err) throw err;
console.log('The solution is: ', rows[0].username);
});
// 關閉數(shù)據(jù)庫
connection.end();
/*
數(shù)據(jù)庫基本操作步驟-查詢操作
*/
const mysql = require('mysql');
// 創(chuàng)建數(shù)據(jù)庫連接
let connection = mysql.createConnection({
host: 'localhost', //數(shù)據(jù)庫所在的服務器域名或者IP
user: 'root', //用戶名
password: '', //密碼
database: 'book' //數(shù)據(jù)庫名稱
});
// 執(zhí)行連接動作
connection.connect();
// 執(zhí)行數(shù)據(jù)庫操作
let sql = 'select * from user where id=?';
let data = [1];
connection.query(sql,data, (err, rows, fields) => {
if (err) throw err;
console.log('The solution is: ', rows[0]);
});
// 關閉數(shù)據(jù)庫
connection.end();
/*
數(shù)據(jù)庫基本操作步驟-插入操作
*/
const mysql = require('mysql');
// 創(chuàng)建數(shù)據(jù)庫連接
let connection = mysql.createConnection({
host: 'localhost', //數(shù)據(jù)庫所在的服務器域名或者IP
user: 'root', //用戶名
password: '', //密碼
database: 'book' //數(shù)據(jù)庫名稱
});
// 執(zhí)行連接動作
connection.connect();
// 執(zhí)行數(shù)據(jù)庫操作
let sql = 'insert into user set ?';
let data = {
username : 'lisi',
password : '111',
age : 12
}
connection.query(sql,data,(err, rows, fields) => {
if (err) throw err;
console.log('The solution is: ', rows.affectedRows);
});
// 關閉數(shù)據(jù)庫
connection.end();
/*
數(shù)據(jù)庫基本操作步驟-刪除操作
*/
const mysql = require('mysql');
// 創(chuàng)建數(shù)據(jù)庫連接
let connection = mysql.createConnection({
host: 'localhost', //數(shù)據(jù)庫所在的服務器域名或者IP
user: 'root', //用戶名
password: '', //密碼
database: 'book' //數(shù)據(jù)庫名稱
});
// 執(zhí)行連接動作
connection.connect();
// 執(zhí)行數(shù)據(jù)庫操作
let sql = 'delete from user where id=?';
let data = [10];
connection.query(sql,data,(err, rows, fields) => {
if (err) throw err;
console.log('The solution is: ', rows.affectedRows);
});
// 關閉數(shù)據(jù)庫
connection.end();
/*
數(shù)據(jù)庫基本操作步驟-更新操作
*/
const mysql = require('mysql');
// 創(chuàng)建數(shù)據(jù)庫連接
let connection = mysql.createConnection({
host: 'localhost', //數(shù)據(jù)庫所在的服務器域名或者IP
user: 'root', //用戶名
password: '', //密碼
database: 'book' //數(shù)據(jù)庫名稱
});
// 執(zhí)行連接動作
connection.connect();
// 執(zhí)行數(shù)據(jù)庫操作
let sql = 'update user set username=?,password=?,age=? where id=?';
let data = ['zhangsan','123456',15,9];
connection.query(sql,data,(err, rows, fields) => {
if (err) throw err;
console.log('The solution is: ', rows.affectedRows);
});
// 關閉數(shù)據(jù)庫
connection.end();