编写代码仅需两个文件。
#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)
}
}
运行结果如下: