android studio数据库内容增删改查的代码
时间: 2023-07-28 16:52:16 浏览: 148
android studio 数据库的增删查改
4星 · 用户满意度95%
以下是使用 Android Studio 操作 SQLite 数据库进行增删改查的示例代码:
1. 创建数据库帮助类
```
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE mytable ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT,"
+ "age INTEGER)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String DROP_TABLE = "DROP TABLE IF EXISTS mytable";
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
```
2. 插入数据
```
DatabaseHelper dbHelper = new DatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "张三");
values.put("age", 20);
long rowId = db.insert("mytable", null, values);
```
3. 查询数据
```
DatabaseHelper dbHelper = new DatabaseHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] projection = {"id", "name", "age"};
String selection = "age > ?";
String[] selectionArgs = {"18"};
String sortOrder = "age DESC";
Cursor cursor = db.query("mytable", projection, selection, selectionArgs, null, null, sortOrder);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
int age = cursor.getInt(cursor.getColumnIndexOrThrow("age"));
Log.d(TAG, "id: " + id + ", name: " + name + ", age: " + age);
}
cursor.close();
```
4. 更新数据
```
DatabaseHelper dbHelper = new DatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "李四");
values.put("age", 21);
String selection = "id = ?";
String[] selectionArgs = {"1"};
int count = db.update("mytable", values, selection, selectionArgs);
```
5. 删除数据
```
DatabaseHelper dbHelper = new DatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
String selection = "age < ?";
String[] selectionArgs = {"20"};
int count = db.delete("mytable", selection, selectionArgs);
```
阅读全文