andriod实现SQLite增删改查,增加并判断元素是否存在,修改若元素不存在则添加
时间: 2024-05-05 17:14:56 浏览: 14
好的,这是一道编程问题。可以通过以下代码实现:
1. 首先创建一个SQLite数据库对象:
```
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(context.getFilesDir().toString() + "/test.db", null);
```
这里的 context 是当前Activity的上下文。
2. 然后创建一个表:
```
db.execSQL("CREATE TABLE IF NOT EXISTS test (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)");
```
3. 增加一个元素并判断是否存在:
```
ContentValues values = new ContentValues();
values.put("name", "张三");
values.put("age", 18);
long result = db.insertWithOnConflict("test", null, values, SQLiteDatabase.CONFLICT_IGNORE);
if (result == -1) {
// 插入失败,说明该元素已存在
} else {
// 插入成功,说明该元素不存在,已经添加到数据库
}
```
4. 修改一个元素:
```
ContentValues values = new ContentValues();
values.put("age", 19);
int result = db.update("test", values, "name=?", new String[]{"张三"});
if (result == 0) {
// 更新失败,说明该元素不存在
} else {
// 更新成功,说明该元素已经被更新
}
```
以上就是基本的SQLite增删改查操作,你可以根据自己的需求进行扩展。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)