当前位置:   article > 正文

HarmonyOS之sqlite数据库的使用_鸿蒙开发连接本地sqlite数据库

鸿蒙开发连接本地sqlite数据库

从API Version 9开始,鸿蒙开发中sqlite使用新接口@ohos.data.relationalStore

但是  relationalStore在 getRdbStore操作时,在预览模式运行或者远程模拟器运行都会报错,导致无法使用。查了一圈说只有在真机上可以正常使用,因此这里暂且使用 @ohos.data.rdb

二者的接口非常相似,会使用了ohos.data.rdb,自然也会使用ohos.data.relationalStore

在harmonyos开发中,操作数据库时,我们通常习惯将一个功能模块数据库操作全部写在一个ets文件中并export,在界面文件中直接导入使用。

1.数据库配置以及建表

新建userDb.ets文件并添加以下代码

  1. import data_rdb from '@ohos.data.rdb'
  2. const STORE_CONFIG = {name: "test.db"}
  3. const TAB_USER = "user"
  4. const CREATE_TABLE_CODE = "CREATE TABLE IF NOT EXISTS "+TAB_USER+" ("
  5. + "id INTEGER PRIMARY KEY AUTOINCREMENT, "
  6. + "name TEXT , "
  7. + "age TEXT , "
  8. + "sex TEXT ) "
  9. export function createTable(context) {
  10. data_rdb.getRdbStore(context,STORE_CONFIG, 1, function (err, rdbStore) {
  11. rdbStore.executeSql(CREATE_TABLE_CODE)
  12. console.info('create table done.')
  13. })
  14. }

在User.ets界面导入并调用 

  1. import {createTable} from '../utils/userDb'
  2. aboutToAppear() {
  3. createTable(getContext(this))
  4. }

2.插入数据

userDb.ets文件添加 insertData方法,这里需要注意的是promise的用法,因为需要将执行结果返回界面,所以方法里面多次使用了Promise来返回结果

插入的字段要和数据库字段保持一致。

  1. export function insertData(context,list):any{
  2. const promise = data_rdb.getRdbStore(context,STORE_CONFIG, 1)
  3. return promise.then(async (rdbStore) => {
  4. let arr:any = [];
  5. for(let i:number=0; i<list.length; i++){
  6. const obj = list[i]
  7. const item ={
  8. name: obj.name,
  9. age: obj.age,
  10. sex: obj.sex
  11. }
  12. rdbStore.insert(TAB_USER, item);
  13. }
  14. console.log('--start')
  15. console.log('完了')
  16. return true;
  17. })
  18. }

 在User.ets界面导入并调用 

  1. import {insertData} from '../utils/userDb'
  2. addData(){
  3. let array = [];
  4. for(let i=0; i<20; i++){
  5. array.push({
  6. name:'张飞'+i,
  7. age: 20+i,
  8. sex: '男'
  9. })
  10. }
  11. insertData(getContext(this), array)
  12. .then(res=>{
  13. if(res){
  14. this.loading = false
  15. this.showDialog('添加成功')
  16. this.search(true)
  17. }
  18. })
  19. }

3.查询

userDb.ets文件添加 queryDataPage方法,这里用了分页查询的方式,还有一种谓词的查询方式请参考官方文档。

  1. export function queryDataPage(context,param):any {
  2. let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1)
  3. return promise.then(async (rdbStore) => {
  4. const sql: string = "select * from "+TAB_USER+" where name like ? " +
  5. "order by id asc limit ? OFFSET ? ";
  6. console.log('----sql---', sql)
  7. const pS = param.pageSize
  8. const page = param.page
  9. console.log('param.code', param.code)
  10. console.log('pS', pS)
  11. console.log('(page-1)*pS', (page - 1) * pS)
  12. // param.code,pS,(page-1)*pS]
  13. let promisequery = rdbStore.querySql(sql, [param.code, pS, (page - 1) * pS])
  14. return promisequery.then(async (resultSet) => {
  15. const rowCount = resultSet.rowCount;
  16. let list = [];
  17. console.log("rowCount --" + rowCount)
  18. resultSet.goToFirstRow();
  19. for (let i = 0; i < rowCount; i++) {
  20. const name = resultSet.getString(resultSet.getColumnIndex("NAME"))
  21. const age = resultSet.getString(resultSet.getColumnIndex("AGE"))
  22. const sex = resultSet.getString(resultSet.getColumnIndex("SEX"))
  23. const id = resultSet.getString(resultSet.getColumnIndex("ID"))
  24. resultSet.goToNextRow();
  25. const data = {
  26. name,
  27. id,
  28. age,
  29. sex,
  30. }
  31. list.push(data);
  32. }
  33. resultSet.close();
  34. console.log('--array--', list.length)
  35. return list;
  36. })
  37. }).catch((err) => {
  38. console.log("Get RdbStore failed, err: " + err)
  39. })
  40. }

在User.ets界面导入并调用 

  1. import {queryDataPage} from '../utils/userDb'
  2. @State list:Array<any> = []
  3. @State keyword:string = ""
  4. @State page:number = 1
  5. @State pageSize:number = 20
  6. search(firstPage:boolean){
  7. if(firstPage){
  8. this.page = 1
  9. }
  10. const params = {
  11. code: '%'+this.keyword+'%',
  12. page: this.page,
  13. pageSize: this.pageSize,
  14. }
  15. queryDataPage(getContext(this), params)
  16. .then(data=>{
  17. if(data){
  18. console.log('res',JSON.stringify(data));
  19. if(this.page == 1){
  20. this.list = data
  21. } else {
  22. this.list = this.list.concat(data);
  23. }
  24. }
  25. })
  26. }

4.更新数据

userDb.ets文件添加 updateData方法

  1. export function updateData(context,newInfo):any{
  2. const promise = data_rdb.getRdbStore(context,STORE_CONFIG, 1)
  3. return promise.then(async (rdbStore) => {
  4. let predicates = new data_rdb.RdbPredicates(TAB_USER);
  5. predicates.equalTo("id", newInfo.id)
  6. let promiseUp = rdbStore.update(newInfo, predicates)
  7. return promiseUp.then(async (rows) => {
  8. if(rows == 1){
  9. return true
  10. }
  11. }).catch((err) => {
  12. console.info("Updated failed, err: " + err)
  13. return false
  14. })
  15. })
  16. }

在User.ets界面导入并调用 

  1. import {updateData} from '../utils/userDb'
  2. updateOne(item:any){
  3. item.name = '张飞111'
  4. updateData(getContext(this), item)
  5. .then(res=>{
  6. if(res){
  7. this.showDialog('更新成功')
  8. this.search(true)
  9. }
  10. })
  11. }

5.删除数据

userDb.ets文件添加 deleteOneData方法

  1. export function deteteOneData(context,id):any{
  2. const promise = data_rdb.getRdbStore(context,STORE_CONFIG, 1)
  3. return promise.then(async (rdbStore) => {
  4. let predicates = new data_rdb.RdbPredicates(TAB_USER);
  5. predicates.equalTo("id", id)
  6. const result = rdbStore.delete(predicates);
  7. console.log('--result--'+JSON.stringify(result))
  8. return true;
  9. })
  10. }

在User.ets界面导入并调用 

  1. import {deteteOneData} from '../utils/userDb'
  2. deleteOne(id:string){
  3. deteteOneData(getContext(this), id)
  4. .then(res=>{
  5. if(res){
  6. this.showDialog('删除成功')
  7. this.search(true)
  8. }
  9. })
  10. }

6.界面效果

点击右上角Add按钮,插入数据;

点击删除按钮,删除一条数据;

点击编辑按钮,将该条数据姓名字段更新为 马超000。

7.完整代码

界面文件 User.ets

  1. import {createTable,insertData,
  2. deteteOneData,updateData,
  3. queryDataPage} from '../utils/userDb'
  4. @Entry
  5. @Component
  6. struct User {
  7. controller: SearchController = new SearchController()
  8. @State codeList:Array<any> = [];
  9. @State list:Array<any> = [];
  10. @State loading:boolean = false;
  11. @State keyword:string = "";
  12. @State page:number = 1;
  13. @State pageSize:number = 20;
  14. aboutToAppear() {
  15. createTable(getContext(this))
  16. }
  17. onReachEnd(){
  18. console.log('--------onReachEnd---');
  19. //this.page = this.page+1
  20. this.search(false)
  21. }
  22. search(firstPage:boolean){
  23. if(firstPage){
  24. this.page = 1
  25. }
  26. const params = {
  27. code: '%'+this.keyword+'%',
  28. page: this.page,
  29. pageSize: this.pageSize,
  30. }
  31. queryDataPage(getContext(this), params)
  32. .then(data=>{
  33. if(data){
  34. console.log('res',JSON.stringify(data));
  35. if(this.page == 1){
  36. this.list = data
  37. } else {
  38. this.list = this.list.concat(data);
  39. }
  40. }
  41. })
  42. }
  43. addData(){
  44. let array = [];
  45. for(let i=0; i<20; i++){
  46. array.push({
  47. name:'张飞'+i,
  48. age: 20+i,
  49. sex: '男'
  50. })
  51. }
  52. insertData(getContext(this), array)
  53. .then(res=>{
  54. if(res){
  55. this.loading = false
  56. this.showDialog('添加成功')
  57. this.search(true)
  58. }
  59. })
  60. }
  61. deleteOne(id:string){
  62. deteteOneData(getContext(this), id)
  63. .then(res=>{
  64. if(res){
  65. this.showDialog('删除成功')
  66. this.search(true)
  67. }
  68. })
  69. }
  70. updateOne(item:any){
  71. item.name = '马超000'
  72. updateData(getContext(this), item)
  73. .then(res=>{
  74. if(res){
  75. this.showDialog('更新成功')
  76. this.search(true)
  77. }
  78. })
  79. }
  80. showDialog(text:string){
  81. AlertDialog.show(
  82. {
  83. title: '提示',
  84. message: text,
  85. autoCancel: true,
  86. alignment: DialogAlignment.Center,
  87. gridCount: 4,
  88. offset: { dx: 0, dy: -20 },
  89. primaryButton: {
  90. value: '确定',
  91. action: () => {
  92. console.info('Callback when the first button is clicked')
  93. }
  94. },
  95. }
  96. )
  97. }
  98. toAddData(){
  99. AlertDialog.show(
  100. {
  101. title: '提示',
  102. message: '确定要添加数据吗',
  103. autoCancel: true,
  104. alignment: DialogAlignment.Center,
  105. offset: { dx: 0, dy: -20 },
  106. gridCount: 5,
  107. primaryButton: {
  108. value: '确定',
  109. action: () => {
  110. console.info('确定 is clicked')
  111. this.loading = true
  112. this.addData()
  113. }
  114. },
  115. secondaryButton: {
  116. value: '取消',
  117. action: () => {
  118. console.info('取消 is clicked')
  119. }
  120. },
  121. cancel: () => {
  122. console.info('Closed callbacks')
  123. }
  124. }
  125. )
  126. }
  127. @Builder NavigationMenus() {
  128. Row() {
  129. Text("Add")
  130. .width(32)
  131. .height(28)
  132. .onClick(()=>this.toAddData())
  133. }
  134. }
  135. @Builder buildList(){
  136. Row(){
  137. Text('姓名')
  138. Text('年龄')
  139. Text('性别')
  140. Text('操作')
  141. }.justifyContent(FlexAlign.SpaceAround)
  142. .width('100%')
  143. .padding({top:5,bottom: 10})
  144. List({ space: 20, initialIndex: 0 }) {
  145. ForEach(this.list, (item) => {
  146. ListItem() {
  147. Row(){
  148. Text(item.name)
  149. Text(item.age)
  150. Text(item.sex)
  151. Row(){
  152. Text('删除').onClick(()=>{
  153. this.deleteOne(item.id)
  154. }).fontColor(Color.Red)
  155. .margin({right:5})
  156. Text('编辑').onClick(()=>{
  157. this.updateOne(item)
  158. }).fontColor(Color.Blue)
  159. }
  160. }
  161. .justifyContent(FlexAlign.SpaceAround)
  162. .width('100%')
  163. }.editable(true)
  164. }, item => item.name)
  165. }
  166. .onScrollIndex((firstIndex: number, lastIndex: number) => {
  167. //console.info('first' + firstIndex)
  168. //console.info('last' + lastIndex)
  169. })
  170. .onReachEnd(()=>{
  171. this.onReachEnd()
  172. })
  173. .listDirection(Axis.Vertical) // 排列方向
  174. .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // 每行之间的分界线
  175. .edgeEffect(EdgeEffect.None) // 滑动到边缘无效果
  176. .chainAnimation(false) // 联动特效关闭
  177. .width('100%')
  178. }
  179. @Builder buildSearch(){
  180. Search({ value: this.keyword, placeholder: '请输入姓名...', controller: this.controller })
  181. .searchButton('搜索')
  182. .width('100%')
  183. .height(40)
  184. .backgroundColor('#F5F5F5')
  185. .placeholderColor(Color.Grey)
  186. .placeholderFont({ size: 14, weight: 400 })
  187. .textFont({ size: 14, weight: 400 })
  188. .onSubmit((value: string) => {
  189. console.log('---999')
  190. //this.submitValue = value
  191. this.keyword = value
  192. this.search(true)
  193. })
  194. .onChange((value: string) => {
  195. this.keyword = value
  196. })
  197. }
  198. build() {
  199. Column(){
  200. Navigation() {
  201. Column(){
  202. this.buildSearch()
  203. if(this.loading){
  204. Column(){
  205. LoadingProgress()
  206. .color(Color.Blue)
  207. }
  208. .width('40%').height('40%')
  209. }
  210. this.buildList()
  211. }.height('100%')
  212. }
  213. .title("用户管理")
  214. .menus(this.NavigationMenus)
  215. .titleMode(NavigationTitleMode.Mini)
  216. }
  217. .height('100%')
  218. }
  219. }

数据操作文件 userDb.ets

  1. import data_rdb from '@ohos.data.rdb'
  2. const STORE_CONFIG = {name: "test.db"}
  3. const TAB_USER = "user"
  4. const CREATE_TABLE_CODE = "CREATE TABLE IF NOT EXISTS "+TAB_USER+" ("
  5. + "id INTEGER PRIMARY KEY AUTOINCREMENT, "
  6. + "name TEXT , "
  7. + "age TEXT , "
  8. + "sex TEXT ) "
  9. export function createTable(context) {
  10. data_rdb.getRdbStore(context,STORE_CONFIG, 1, function (err, rdbStore) {
  11. rdbStore.executeSql(CREATE_TABLE_CODE)
  12. console.info('create table done.')
  13. })
  14. }
  15. export function updateData(context,newInfo):any{
  16. const promise = data_rdb.getRdbStore(context,STORE_CONFIG, 1)
  17. return promise.then(async (rdbStore) => {
  18. let predicates = new data_rdb.RdbPredicates(TAB_USER);
  19. predicates.equalTo("id", newInfo.id)
  20. let promiseUp = rdbStore.update(newInfo, predicates)
  21. return promiseUp.then(async (rows) => {
  22. if(rows == 1){
  23. return true
  24. }
  25. }).catch((err) => {
  26. console.info("Updated failed, err: " + err)
  27. return false
  28. })
  29. })
  30. }
  31. export function insertData(context,list):any{
  32. const promise = data_rdb.getRdbStore(context,STORE_CONFIG, 1)
  33. return promise.then(async (rdbStore) => {
  34. let arr:any = [];
  35. for(let i:number=0; i<list.length; i++){
  36. const obj = list[i]
  37. const item ={
  38. name: obj.name,
  39. age: obj.age,
  40. sex: obj.sex
  41. }
  42. rdbStore.insert(TAB_USER, item);
  43. }
  44. console.log('--start')
  45. console.log('完了')
  46. return true;
  47. })
  48. }
  49. export function deteteOneData(context,id):any{
  50. const promise = data_rdb.getRdbStore(context,STORE_CONFIG, 1)
  51. return promise.then(async (rdbStore) => {
  52. let predicates = new data_rdb.RdbPredicates(TAB_USER);
  53. predicates.equalTo("id", id)
  54. const result = rdbStore.delete(predicates);
  55. console.log('--result--'+JSON.stringify(result))
  56. return true;
  57. })
  58. }
  59. export function detelteAllCode(context){
  60. data_rdb.getRdbStore(context,STORE_CONFIG, 1, function (err, rdbStore) {
  61. rdbStore.executeSql("delete from "+TAB_USER)
  62. console.info('--delete code done.')
  63. })
  64. }
  65. export function queryDataPage(context,param):any {
  66. let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1)
  67. return promise.then(async (rdbStore) => {
  68. const sql: string = "select * from "+TAB_USER+" where name like ? " +
  69. "order by id asc limit ? OFFSET ? ";
  70. console.log('----sql---', sql)
  71. const pS = param.pageSize
  72. const page = param.page
  73. console.log('param.code', param.code)
  74. console.log('pS', pS)
  75. console.log('(page-1)*pS', (page - 1) * pS)
  76. // param.code,pS,(page-1)*pS]
  77. let promisequery = rdbStore.querySql(sql, [param.code, pS, (page - 1) * pS])
  78. return promisequery.then(async (resultSet) => {
  79. const rowCount = resultSet.rowCount;
  80. let list = [];
  81. console.log("rowCount --" + rowCount)
  82. resultSet.goToFirstRow();
  83. for (let i = 0; i < rowCount; i++) {
  84. const name = resultSet.getString(resultSet.getColumnIndex("NAME"))
  85. const age = resultSet.getString(resultSet.getColumnIndex("AGE"))
  86. const sex = resultSet.getString(resultSet.getColumnIndex("SEX"))
  87. const id = resultSet.getString(resultSet.getColumnIndex("ID"))
  88. resultSet.goToNextRow();
  89. const data = {
  90. name,
  91. id,
  92. age,
  93. sex,
  94. }
  95. list.push(data);
  96. }
  97. resultSet.close();
  98. console.log('--array--', list.length)
  99. return list;
  100. })
  101. }).catch((err) => {
  102. console.log("Get RdbStore failed, err: " + err)
  103. })
  104. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/264453
推荐阅读
相关标签
  

闽ICP备14008679号