database.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. //打开数据库(创建数据库或者有该数据库就打开)
  2. var name = "sample_storage" // 数据库名称
  3. // 防止数据中的 单引号 报错
  4. export function html2Escape(str) {
  5. // console.log("str",str,typeof str)
  6. if(typeof str === "string"){
  7. return str.replace(/'/g, "''");
  8. }else if(typeof str === "object"){
  9. return JSON.stringify(str).replace(/'/g, "''");
  10. }else{
  11. return str
  12. }
  13. }
  14. export async function openSqlite(){
  15. //创建数据库或者打开
  16. //这plus.sqlite只在手机上运行
  17. return new Promise((resolve,reject) =>{
  18. if(isOpen()){
  19. // console.log("数据库已经打开了")
  20. resolve("数据库已经打开");
  21. return true
  22. }
  23. // console.log("开始打开数据库")
  24. plus.sqlite.openDatabase({
  25. name, //数据库名称
  26. path:`_doc/${name}.db`, //数据库地址,uniapp推荐以下划线为开头,这到底存在哪里去了,我也不清楚,哈哈
  27. success(){
  28. // console.log("成功打开数据库")
  29. resolve(); //成功回调
  30. },
  31. fail(e){
  32. // console.log("失败打开数据库",e)
  33. reject(e); //失败回调
  34. }
  35. })
  36. })
  37. }
  38. //判断数据库是否打开
  39. export function isOpen(){
  40. //数据库打开了就返回true,否则返回false
  41. var open = plus.sqlite.isOpenDatabase({
  42. name,
  43. path: `_doc/${name}.db`
  44. })
  45. return open;
  46. }
  47. //关闭数据库
  48. export function closedb(){
  49. return new Promise((resolve,reject) =>{
  50. plus.sqlite.closeDatabase({
  51. name,
  52. success(e){
  53. resolve(e);
  54. },
  55. fail(e){
  56. reject(e);
  57. }
  58. })
  59. })
  60. }
  61. // 执行sql语句
  62. export function executeSql(sql){
  63. return new Promise((resolve,reject) =>{
  64. //创建表格在executeSql方法里写
  65. // console.log("开始执行自定义sql",sql)
  66. plus.sqlite.executeSql({
  67. name,
  68. //表格创建或者打开,后面为表格结构
  69. sql:sql,
  70. success(e){
  71. resolve(e);
  72. },
  73. fail(e){
  74. console.error("自定义sql报错",e)
  75. reject(e);
  76. }
  77. })
  78. })
  79. }
  80. // 查询所有数据表名
  81. export async function getTable(){
  82. return selectSql("select * FROM sqlite_master where type='table'")
  83. }
  84. // 获取表的所有字段
  85. export async function getAllField(tableName){
  86. return selectSql(`PRAGMA table_info([${tableName}])`)
  87. }
  88. // 查询表数据总条数
  89. export const getCount = (tableName,whereObj={}) => {
  90. let sql = `select count(*) as num from ${tableName} where 1 `
  91. if(Object.keys(whereObj).length>0){
  92. for(let i in whereObj){
  93. sql += ` and ${i} = '${whereObj[i]}' `
  94. }
  95. }
  96. console.log("getCount的SQL",sql)
  97. return selectSql(sql)
  98. }
  99. // 查询表是否存在
  100. export const isTable = (tableName) => {
  101. return new Promise((resolve, reject) => {
  102. plus.sqlite.selectSql({
  103. name: name,
  104. sql: `select count(*) as isTable FROM sqlite_master where type='table' and name='${tableName}'`,
  105. success(e) {
  106. resolve(e[0].isTable ? true : false);
  107. },
  108. fail(e) {
  109. console.log(e)
  110. reject(e);
  111. }
  112. })
  113. })
  114. }
  115. // 添加数据
  116. export async function addSql(tableName,obj={}) {
  117. if (Object.keys(obj).length>0) {
  118. // 获取数据库的字段
  119. let fieldList = await getAllField(tableName)
  120. // 取数据库有的字段
  121. let keys = intersection(fieldList,obj)
  122. let keyStr = keys.toString()
  123. let valStr = ''
  124. keys.forEach((item, index) => {
  125. valStr += (`'${html2Escape(obj[item])}',`)
  126. })
  127. valStr = valStr.substring(0,valStr.length-1)
  128. let sqlStr = `insert into ${tableName}(${keyStr}) values(${valStr})`
  129. console.log("addSql",sqlStr)
  130. return executeSql(sqlStr)
  131. } else {
  132. return new Promise((resolve, reject) => {
  133. reject("错误")
  134. })
  135. }
  136. }
  137. // 修改数据
  138. export async function updateSql(tableName, setData, whereObj={}){
  139. if(!Object.keys(whereObj).length){
  140. return new Promise((resolve, reject) => {
  141. reject("请传whereObj")
  142. });
  143. return false
  144. }
  145. if (setData&&JSON.stringify(setData) !== '{}') {
  146. // 获取数据库的字段
  147. let fieldList = await getAllField(tableName)
  148. let dataKeys = intersection(fieldList,setData)
  149. let setStr = ''
  150. // console.log("dataKeys",tableName,dataKeys)
  151. dataKeys.forEach((item, index) => {
  152. // console.log(setData[item])
  153. setStr += (
  154. `${item} = '${setData[item]}',`)
  155. })
  156. setStr = setStr.substring(0,setStr.length-1)
  157. let sql = `update ${tableName} set ${setStr} where 1 `
  158. for(let i in whereObj){
  159. sql += ` and ${i} = '${whereObj[i]}' `
  160. }
  161. // console.log("修改数据的sql",sql)
  162. return executeSql(sql)
  163. } else {
  164. return new Promise((resolve, reject) => {
  165. reject("错误")
  166. });
  167. }
  168. }
  169. //删除数据库数据
  170. export async function deleteSql(tableName,whereObj={}){
  171. if (tableName&&JSON.stringify(whereObj) !== '{}') {
  172. let dataKeys = Object.keys(whereObj)
  173. let setStr = ''
  174. dataKeys.forEach((item, index) => {
  175. console.log(whereObj[item])
  176. setStr += (
  177. `${item}='${whereObj[item]}' ${dataKeys.length - 1 !== index ? " and " : ""}`)
  178. })
  179. console.log("删除sql",`-- delete from ${tableName} where ${setStr}`)
  180. let sql = `delete from ${tableName} where ${setStr}`
  181. return executeSql(sql)
  182. } else {
  183. return new Promise((resolve, reject) => {
  184. reject("错误")
  185. });
  186. }
  187. }
  188. /**
  189. * 获取分页数据库数据
  190. * @param tableName 表名称
  191. * @param pageObj 分页数据,如 {current:1,size:10}
  192. * @param whereObj 查询
  193. * @param orderBy 排序
  194. * @returns {Promise<unknown>}
  195. */
  196. export const getPageList = async (tableName,pageObj,whereObj={},orderBy) => {
  197. // console.log("数据库",tableName,pageObj,whereObj,orderBy)
  198. let current = parseInt(pageObj.current)
  199. let size = parseInt(pageObj.size)
  200. // console.log("数据库11")
  201. let pages = 0,total = 0 // pages为总页数,total为总数据条数
  202. let sql = ''
  203. let numindex = 0
  204. await getCount(tableName,whereObj).then((resNum) => {
  205. console.log("resNum",resNum,size)
  206. pages = Math.ceil(resNum[0].num / size)
  207. total = resNum[0].num
  208. })
  209. if(((current - 1) * size) == 0) {
  210. numindex = 0
  211. } else {
  212. numindex = ((current - 1) * size) + 1
  213. }
  214. sql = `select * from ${tableName} where 1 `
  215. if(Object.keys(whereObj).length>0){
  216. for(let i in whereObj){
  217. sql += ` and ${i} = '${whereObj[i]}' `
  218. }
  219. }
  220. if(orderBy) {
  221. sql += ` order by ${orderBy} `
  222. }
  223. sql += ` limit ${numindex},${size}`
  224. console.log("分页sql,",sql)
  225. if (pages < current - 1) {
  226. return new Promise((resolve, reject) => {
  227. reject("无数据")
  228. });
  229. } else {
  230. return new Promise((resolve, reject) => {
  231. plus.sqlite.selectSql({
  232. name: name,
  233. sql:sql ,
  234. success(e) {
  235. resolve({
  236. code:0,
  237. data:{
  238. data:{
  239. records:e,
  240. pages,
  241. total
  242. }
  243. },
  244. msg:null
  245. });
  246. },
  247. fail(e) {
  248. reject({data:e,code:500,msg:e});
  249. }
  250. })
  251. })
  252. }
  253. }
  254. /**
  255. * 自定义语句查询,数据库数据
  256. * @param sql sql语句
  257. * @returns {Promise<any>}
  258. */
  259. export const selectSql = (sql) => {
  260. // console.log("查询的sql",sql)
  261. return new Promise((resolve, reject) => {
  262. plus.sqlite.selectSql({
  263. name: name,
  264. sql: sql,
  265. success(e) {
  266. resolve(e);
  267. },
  268. fail(e) {
  269. console.log("查询报错",e)
  270. reject(e);
  271. }
  272. })
  273. })
  274. }
  275. /**
  276. * 查询数据库数据
  277. * @param tableName 表名
  278. * @param searchObj 查询的对象
  279. * @param orderBy 排序, 如 "id desc"
  280. * @param selectStr
  281. * @returns {Promise<any>}
  282. */
  283. export const selectList = (tableName,searchObj={},orderBy="") => {
  284. let setStr = ''
  285. let sql = ''
  286. if (tableName) {
  287. if (JSON.stringify(searchObj) !== '{}') {
  288. let dataKeys = Object.keys(searchObj)
  289. dataKeys.forEach((item, index) => {
  290. // console.log(searchObj[item])
  291. setStr += (
  292. `${item}='${html2Escape(searchObj[item])}' ${dataKeys.length - 1 !== index ? " and " : ""}`)
  293. })
  294. }
  295. sql = `select * from ${tableName} `
  296. sql += setStr ? ` where ${setStr} ` : ""
  297. if(orderBy) {
  298. sql += ` order by ${orderBy} `
  299. }
  300. console.log("查询数据库数据",sql)
  301. return selectSql(sql)
  302. } else {
  303. return new Promise((resolve, reject) => {
  304. reject("错误")
  305. });
  306. }
  307. }
  308. //将SQL语句进行拼接values(),()...然后再一次性插入,
  309. export async function insertAll(tableName="",data=[]){
  310. let sql = ""
  311. // 获取数据库的字段
  312. try{
  313. let fieldList = await getAllField(tableName)
  314. // console.log("fieldList",fieldList)
  315. if (tableName && data.length > 0) {
  316. // 取交集的字段,才是合法的,能存进数据库的字段(注意:取的字段,是按照第一条数据的字段,进行赋值的)
  317. let keys = intersection(fieldList,data[0])
  318. let keyStr = keys.toString()
  319. console.log("keyStr",keyStr)
  320. sql = `insert into ${tableName} (${keyStr}) values`;
  321. for (let i = 0; i < data.length; i++) {
  322. sql += "(";
  323. for (const [k, v] of keys.entries()) {
  324. // console.log("data[i][v]",k,v,data[i][v],data)
  325. sql += `'${html2Escape(data[i][v])}',`
  326. }
  327. sql = sql.substring(0, sql.length - 1)
  328. sql += "),";
  329. }
  330. sql = sql.substring(0, sql.length - 1)
  331. console.log("批量插入的sql", sql)
  332. } else {
  333. this.$msg("表名为空或者插入数据为空")
  334. }
  335. }catch(e){
  336. console.error("批量插入报错",e)
  337. }
  338. return executeSql(sql)
  339. }
  340. /**
  341. * 批量修改 data数组 field关键字段 批量修改函数 传参方式
  342. * @param tableName 表名
  343. * @param data 需要修改的数据
  344. * @param field 表主键字段,通常是 id
  345. * @returns {Promise<unknown>}
  346. */
  347. export async function batchUpdate(tableName='',data=[],field=''){
  348. let sql = ""
  349. let con = [];
  350. let con_sql = [];
  351. let fields = [];
  352. let value
  353. let temp
  354. try{
  355. if (!tableName || !data || !field) {
  356. return false;
  357. } else {
  358. sql = 'UPDATE ' + tableName;
  359. }
  360. for (let key in data) {
  361. value = data[key]
  362. let x = 0;
  363. let v
  364. // console.log("value",value)
  365. for (let k in value) {
  366. v = value[k]
  367. if (k != field && !con[x] && x == 0) {
  368. con[x] = ` set ${k} = (CASE ${field} `;
  369. } else if (k != field && !con[x] && x > 0) {
  370. con[x] = ` ${k} = (CASE ${field} `;
  371. }
  372. if (k != field) {
  373. temp = value[field];
  374. con_sql[x] = con_sql[x] ? con_sql[x] : ""
  375. con_sql[x] += ` WHEN '${temp}' THEN '${html2Escape(v)}' `;
  376. x++;
  377. }
  378. }
  379. temp = value[field];
  380. // console.log("temp",fields,temp)
  381. if (fields.indexOf(temp)===-1) {
  382. fields.push(temp)
  383. }
  384. }
  385. let num = con.length - 1;
  386. for (let [key, value] of con.entries()) {
  387. for (let [k, v] of con_sql.entries()) {
  388. if (k == key && key < num) {
  389. sql += value + v + ' end),';
  390. } else if (k == key && key == num) {
  391. sql += value + v + ' end)';
  392. }
  393. }
  394. }
  395. let str = fields.join(",");
  396. sql += ` where ${field} in(${str})`;
  397. console.log("批量更新的sql", sql)
  398. }catch(e){
  399. console.error("批量修改报错",e)
  400. }
  401. return executeSql(sql)
  402. }
  403. //////////////////////////////////////////////////////////////////////
  404. // 合并数据
  405. export const mergeSql = (name,tableName,tabs) => {
  406. if (!tabs || tabs.length == 0) {
  407. return new Promise((resolve, reject) => {
  408. reject("错误")
  409. })
  410. }
  411. let itemValStr = ''
  412. tabs.forEach((item, index) => {
  413. let itemKey = Object.keys(item)
  414. let itemVal = ''
  415. itemKey.forEach((key, i) => {
  416. if (itemKey.length - 1 == i) {
  417. if (typeof item[key] == 'object') {
  418. itemVal += (`'${JSON.stringify(item[key])}'`)
  419. } else {
  420. itemVal += (`'${item[key]}'`)
  421. }
  422. } else {
  423. if (typeof item[key] == 'object') {
  424. itemVal += (`'${JSON.stringify(item[key])}',`)
  425. } else {
  426. itemVal += (`'${item[key]}',`)
  427. }
  428. }
  429. })
  430. if (tabs.length - 1 == index) {
  431. itemValStr += ('(' + itemVal + ')')
  432. } else {
  433. itemValStr += ('(' + itemVal + '),')
  434. }
  435. })
  436. let keys = Object.keys(tabs[0])
  437. let keyStr = keys.toString()
  438. let sql = `insert or ignore into ${tableName} (${keyStr}) values ${itemValStr}`
  439. return executeSql(sql)
  440. }
  441. /**
  442. * 过滤非数据表的字段,使其不报错
  443. * @param fieldList ,使用 getAllField()函数查询出来的数据
  444. * @param obj 数据
  445. * @returns []
  446. */
  447. export function intersection(fieldList=[],obj){
  448. // 获取数据库的字段
  449. let arrField = {}
  450. for(let i in fieldList){
  451. arrField[fieldList[i].name] = null
  452. }
  453. // 取交集的字段,才是合法的,能存进数据库的字段
  454. let keys = []
  455. for (let i in arrField) {
  456. if (obj.hasOwnProperty(i)) {
  457. keys.push(i)
  458. }
  459. }
  460. return keys
  461. }