在Android中常用的数据库语言是SQLite,这是一种轻型的嵌入式数据库语法。
-
创建数据库:
SQLiteDatabase db = openOrCreateDatabase("myDatabase.db", Context.MODE_PRIVATE, null);
- 创建数据表:
String createTableQuery = "CREATE TABLE IF NOT EXISTS myTable (ID INTEGER PRIMARY KEY, name TEXT, age INTEGER)";
db.execSQL(createTableQuery);
- 插入数据:
String insertDataQuery = "INSERT INTO myTable (name, age) VALUES ('Ali', 27)";
db.execSQL(insertDataQuery);
或者
ContentValues values = new ContentValues();
values.put("name", "Ali");
values.put("age", 27);
db.insert("myTable", null, values);
- 查询数据:
String selectQuery = "SELECT * FROM myTable";
Cursor cursor = db.rawQuery(selectQuery, null);
while (cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
}
cursor.close();
- 更新数据:
String updateQuery = "UPDATE myTable SET age = 28 WHERE name = 'Ali'";
db.execSQL(updateQuery);
或者
ContentValues values = new ContentValues();
values.put("age", 28);
db.update("myTable", values, "name = ?", new String[]{"Ali"});
- 删除数据:
String deleteQuery = "DELETE FROM myTable WHERE name = 'Ali'";
db.execSQL(deleteQuery);
或者
db.delete("myTable", "name = ?", new String[]{"Ali"});
记住每次执行完数据库操作后,都需要关闭数据库:
db.close();
以上就是在Android中常用的SQLite数据库语法。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/172506.html