在HarmonyOS中,可以使用Java語言結合SQLite數(shù)據(jù)庫來進行數(shù)據(jù)庫操作。以下是一個簡單的示例代碼,演示了如何在HarmonyOS中使用Java實現(xiàn)數(shù)據(jù)庫操作:
import ohos.data.DatabaseHelper;
public class MyDatabaseHelper extends DatabaseHelper {
private static final int DATABASE_VERSION = 1;
public MyDatabaseHelper() {
super("", null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 創(chuàng)建表
String createTableQuery = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)";
db.executeSql(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升級數(shù)據(jù)庫
}
}
import ohos.data.DatabaseHelper;
import ohos.data.Database;
public class DatabaseExample {
public void insertUser(String name) {
MyDatabaseHelper dbHelper = new MyDatabaseHelper();
Database database = dbHelper.openOrCreate("example.db");
String insertQuery = "INSERT INTO users (name) VALUES (?)";
database.executeSql(insertQuery, new String[]{name});
database.close();
}
public void queryUsers() {
MyDatabaseHelper dbHelper = new MyDatabaseHelper();
Database database = dbHelper.openOrCreate("example.db");
String query = "SELECT * FROM users";
ResultSet resultSet = database.executeQuery(query);
while (resultSet.goToNextRow()) {
String name = resultSet.getString(resultSet.getColumnIndexForName("name"));
// 處理查詢結果
}
database.close();
}
}
以上示例代碼展示了如何在HarmonyOS中使用Java實現(xiàn)數(shù)據(jù)庫操作。請注意,在實際項目中,建議使用ORM框架(如LitePal)來簡化數(shù)據(jù)庫操作。