一共创建两个鸿蒙文件,一个是page页面login.ets,一个是arkts的WeatherDB.ets。
#login.ets代码:
import { createTable } from '../model/WeatherDB'
@Entry
@Component
struct MainPage {
aboutToAppear() {
const context = getContext(this)
createTable(context)
console.log("🟢 aboutToAppear 调用 createTable")
}
build() {
Column() {
Text('测试页面').fontSize(30)
}
}
}
#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)
}
}
运行结果:
数据库的表创建成功,数据库为
weather.db