最近在項目中須要鏈接數據庫,作增刪改查的功能,sql語句整理作了如下記錄(基於NodeJs,注:data爲你的真實數據):sql
(一)新增插入表中數據:數據庫
sql: 'insert into work(表名) (name,id,src) values(?,?,?);', values: [ //須要插入的對應屬性 data.name, data.id,
data.src, ],
/******example******/
insertWorkList = async (data) => {
return new Promise((resolved, reject) => {
connection.query({
sql: 'insert into work(表名) (name,id,src) values(?,?,?);',
values: [
data.name,
data.id,
data.src,
],
}, (error, results) => {
if (error) {
reject(error);
} else {
resolved(results);
}
});
});
};async
(二)更新表中數據(更新數據須要根據對應的惟一屬性,例如id):spa
sql: 'update work(表名) set name=?, src=? where id=?', values: [ //須要插入的對應屬性 data.name, data.src, data.id, //經過此id去更改name和src ],
/******example******/
updateWorkById = async (data) => {
return new Promise((resolved, reject) => {
connection.query({
sql: 'update work(表名) set name=?, src=? where id=?',
values: [
data.name,
data.src,
data.id,
],
}, (error, results) => {
if (error) {
reject(error);
} else {
resolved(results);
}
});
});
};code
(三)查詢表中的數據:blog
(1)查詢某個表單中全部的數據(注: 查詢全部數據不用傳輸values值) get
select * from work(表名)
/******example******/io
getList = async () => {
return new Promise((resolved, reject) => {
connection.query('select * from work', (error, results) => {
if (error) {
reject(error);
} else {
resolved(results);
}
});
});
};class
(2)經過id或其餘惟一屬性查詢某個表單中的數據表單
sql: 'select * from work where id=?',
values: [id],
/******example******/
getWorkById = async (id) => {
return new Promise((resolved, reject) => {
connection.query({
sql: 'select * from work(表名) where id=?',
values: [id],
}, (error, results) => {
if (error) {
reject(error);
} else {
resolved(results);
}
});
});
};
(四)刪除表中id或其餘惟一屬性對應的數據:
sql: 'delete from work where id=?', values: [id], /******example******/ deleteWorkById = async (id) => { return new Promise((resolved, reject) => { connection.query({ sql: 'delete from work(表名) where id=?', values: [id], }, (error, results) => { if (error) { reject(error); } else { resolved(results); } }); }); };