208 lines
		
	
	
		
			5.6 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
			
		
		
	
	
			208 lines
		
	
	
		
			5.6 KiB
		
	
	
	
		
			TypeScript
		
	
	
	
	
	
| import relationalStore from '@ohos.data.relationalStore'
 | |
| import common from '@ohos.app.ability.common'
 | |
| 
 | |
| export interface ColumnInfo {
 | |
|   name: string,
 | |
|   columnName: string,
 | |
|   type: ColumnType,
 | |
| }
 | |
| 
 | |
| export enum ColumnType {
 | |
|   LONG,
 | |
|   STRING
 | |
| }
 | |
| 
 | |
| class DbUtils {
 | |
|   rdbStore: relationalStore.RdbStore | undefined = undefined
 | |
| 
 | |
|   init(context: common.UIAbilityContext) {
 | |
|     let config: relationalStore.StoreConfig = {
 | |
|       name: 'car.db',
 | |
|       securityLevel: relationalStore.SecurityLevel.S1
 | |
|     }
 | |
|     return new Promise<void>((resolve, reject) => {
 | |
|       relationalStore.getRdbStore(context, config)
 | |
|         .then(rdbStore => {
 | |
|           this.rdbStore = rdbStore
 | |
|           console.info("db rdbStore init success")
 | |
|           resolve()
 | |
|         })
 | |
|         .catch((err: any) => {
 | |
|           console.error(`db rdbStore init fail reason:${err}`);
 | |
|           reject(err)
 | |
|         })
 | |
| 
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   //   创建表
 | |
|   createTable(createSql: string): Promise<void> {
 | |
|     return new Promise((resolve, reject) => {
 | |
|       if (this.rdbStore) {
 | |
|         this.rdbStore?.executeSql(createSql)
 | |
|           .then(() => {
 | |
|             console.info("sql createTable success")
 | |
|             resolve()
 | |
|           })
 | |
|           .catch((err) => {
 | |
|             console.error(`sql createTable fail err:${JSON.stringify(err)}`);
 | |
|             reject(err)
 | |
|           })
 | |
|       } else {
 | |
|         reject('rdbStore is null')
 | |
|       }
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   // 请空表
 | |
|   clearTable(tableName: string): Promise<void> {
 | |
|     let sql = `DELETE FROM ${tableName}`
 | |
|     return new Promise((resolve, reject) => {
 | |
|       if (this.rdbStore) {
 | |
|         this.rdbStore?.executeSql(sql).then(() => {
 | |
|           resolve()
 | |
|         })
 | |
|       } else {
 | |
|         reject('rdbStore is null')
 | |
|       }
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   // 执行sql
 | |
|   executeSql(sql: string): Promise<string> {
 | |
|     return new Promise((resolve, reject) => {
 | |
|       if (this.rdbStore) {
 | |
|         this.rdbStore?.executeSql(sql).then(() => {
 | |
|           resolve("")
 | |
|         }).catch((err) => {
 | |
|           reject(err)
 | |
|         })
 | |
|       } else {
 | |
|         reject('rdbStore is null')
 | |
|       }
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   insertData(tableName: string, obj: any): Promise<number> {
 | |
|     return new Promise((resolve, reject) => {
 | |
|       if (this.rdbStore) {
 | |
|         this.rdbStore?.insert(tableName, obj, (err, res) => {
 | |
|           if (err) {
 | |
|             console.error(`sql insertData fail err:${JSON.stringify(err)}`);
 | |
|             console.error(`sql insertData fail err:tableName=${tableName}content=${JSON.stringify(obj)}`);
 | |
|             reject(err)
 | |
|           } else {
 | |
|             console.info(`sql insertData success res:${res}`);
 | |
|             resolve(res)
 | |
|           }
 | |
|         })
 | |
|       } else {
 | |
|         reject('rdbStore is null')
 | |
|       }
 | |
|     })
 | |
|   }
 | |
| 
 | |
| 
 | |
|   // 插入表数据
 | |
|   // insertData(tableName: string, obj: object, columns: ColumnInfo[]): Promise<number> {
 | |
|   //   return new Promise((resolve, reject) => {
 | |
|   //     if(this.)
 | |
|   //   })
 | |
|   //
 | |
|   // }
 | |
| 
 | |
|   //   查找
 | |
|   queryCount<T extends string | number | boolean>(sql: string): Promise<T> {
 | |
|     return new Promise((resolve, reject) => {
 | |
|       if (this.rdbStore) {
 | |
|         this.rdbStore.querySql(sql, []).then((res: relationalStore.ResultSet) => {
 | |
|           console.log("sql query", JSON.stringify(res))
 | |
|           if (res.rowCount <= 0) {
 | |
|             resolve(null)
 | |
|           } else {
 | |
|             res.goToNextRow()
 | |
|             resolve(res.getLong(0) as unknown as T)
 | |
|           }
 | |
|         }).catch((err) => {
 | |
|           console.error(`sql queryCount fail err:${JSON.stringify(err)}`);
 | |
|           reject(err)
 | |
|         })
 | |
|       } else {
 | |
|         reject('rdbStore is null')
 | |
|       }
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   //   查找数据
 | |
|   queryList<T>(predicates: relationalStore.RdbPredicates, columns: ColumnInfo[]): Promise<T[]> {
 | |
|     return new Promise((resolve, reject) => {
 | |
|       if (this.rdbStore) {
 | |
|         this.rdbStore?.query(predicates, columns.map(info => info.columnName), (err, result) => {
 | |
|           if (err) {
 | |
|             console.error(`sql queryForList fail err:${JSON.stringify(err)}`);
 | |
|             reject(err)
 | |
|           } else {
 | |
|             console.info(`sql queryForList success rows: ${result.rowCount.toString()}`)
 | |
|             resolve(this.parseResultSet(result, columns))
 | |
|           }
 | |
|         })
 | |
|       } else {
 | |
|         reject('rdbStore is null')
 | |
|       }
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   //
 | |
|   queryListBySql<T>(sql: string, columns: ColumnInfo[]): Promise<T[]> {
 | |
|     return new Promise((resolve, reject) => {
 | |
|       if (this.rdbStore) {
 | |
|         this.rdbStore?.querySql(sql, [], (err, result) => {
 | |
|           if (err) {
 | |
|             console.error(`sql queryForListBySql fail err:${JSON.stringify(err)}`);
 | |
|             reject(err)
 | |
|           } else {
 | |
|             resolve(this.parseResultSet(result, columns))
 | |
|           }
 | |
|         })
 | |
|       } else {
 | |
|         reject('rdbStore is null')
 | |
|       }
 | |
|     })
 | |
|   }
 | |
| 
 | |
|   parseResultSet<T>(result: relationalStore.ResultSet, columns: ColumnInfo[]): T[] {
 | |
|     // 1.声明最终返回的结果
 | |
|     let arr: T[] = [];
 | |
|     // 2.判断是否有结果
 | |
|     if (result.rowCount <= 0) {
 | |
|       return arr;
 | |
|     }
 | |
|     // 3.处理结果
 | |
|     while (!result.isAtLastRow) {
 | |
|       // 3.1.去下一行
 | |
|       result.goToNextRow();
 | |
|       // 3.2.解析这行数据,转为对象
 | |
|       let obj: Record<string, string | number> = {};
 | |
|       columns.forEach(info => {
 | |
|         let val: string | number;
 | |
|         switch (info.type) {
 | |
|           case ColumnType.LONG:
 | |
|             val = result.getLong(result.getColumnIndex(info.columnName));
 | |
|             break;
 | |
|           case ColumnType.STRING:
 | |
|             val = result.getString(result.getColumnIndex(info.columnName));
 | |
|             break;
 | |
|         }
 | |
|         obj[info.name] = val;
 | |
|       });
 | |
|       // 3.3.将对象填入结果数组
 | |
|       arr.push(obj as unknown as T); // 将 obj 断言为 T 类型
 | |
|     }
 | |
|     return arr;
 | |
|   }
 | |
| }
 | |
| 
 | |
| let DB: DbUtils = new DbUtils()
 | |
| 
 | |
| export default DB
 |