鸿蒙代码数据库插入一条数据

编写代码仅需两个文件。

#WeatherDB.ets代码如下:

import dataRdb from '@ohos.data.rdb'

const STORE_CONFIG = {
  name: 'weather.db'
}
const TABLE_NAME = 'weather_info'
const SQL_CREATE_TABLE = `
  CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    city TEXT NOT NULL,
    temperature TEXT,
    weather TEXT,
    updateTime TEXT
  )
`
export async function createTable(context) {
  try {
    const store = await dataRdb.getRdbStore(context, STORE_CONFIG, 1)
    await store.executeSql(SQL_CREATE_TABLE)
    console.info(`✅ 表 ${TABLE_NAME} 创建成功`)
  } catch (err) {
    console.error(`❌ 创建表失败: ${JSON.stringify(err)}`)
    console.error('错误详情:', err)
  }
}

#login.ets页面代码:

import dataRdb from '@ohos.data.rdb'
import {createTable} from '../model/WeatherDB'
@Entry
@Component
struct WeatherInsertPage {
  @State city: string = ''
  @State temperature: string = ''
  @State weather: string = ''
  @State updateTime: string = ''

  async insertData() {
    const context = getContext(this)
    createTable(context)
    const rdbStore = await dataRdb.getRdbStore(context, { name: 'weather.db' }, 1)

    const valueBucket: dataRdb.ValuesBucket = {
      city: this.city,
      temperature: this.temperature,
      weather: this.weather,
      updateTime: this.updateTime
    }
    try {
      let rowId = await rdbStore.insert('weather_info', valueBucket)
      console.info(`✅ 插入成功,行ID: ${rowId}`)
    } catch (err) {
      console.error(`❌ 插入失败: ${JSON.stringify(err)}`)
    }
  }

  build() {
    Column() {
      TextInput({ placeholder: '城市名' })
        .onChange((val: string) => this.city = val)
      TextInput({ placeholder: '温度'})
        .onChange((val: string) => this.temperature = val)
      TextInput({ placeholder: '天气状况' })
        .onChange((val: string) => this.weather = val)
      TextInput({ placeholder: '更新时间' })
        .onChange((val: string) => this.updateTime = val)
      Button('插入天气数据')
        .onClick(() => this.insertData())
    }.padding(20)
  }
}

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值