android studio数据库增删查改
时间: 2023-09-16 10:06:42 浏览: 232
在 Android Studio 中进行数据库的增删查改操作,需要使用 SQLite 数据库,以下是一个简单的示例:
1. 创建数据库表
```java
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "mydb";
private static final int DB_VERSION = 1;
public MyDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS user (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS user");
onCreate(db);
}
}
```
2. 添加数据
```java
public void addUser(String name, int age) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
db.insert("user", null, values);
db.close();
}
```
3. 删除数据
```java
public void deleteUser(int id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("user", "_id=?", new String[]{String.valueOf(id)});
db.close();
}
```
4. 修改数据
```java
public void updateUser(int id, String name, int age) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
db.update("user", values, "_id=?", new String[]{String.valueOf(id)});
db.close();
}
```
5. 查询数据
```java
public List<User> queryUsers() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query("user", null, null, null, null, null, null);
List<User> userList = new ArrayList<>();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
User user = new User(id, name, age);
userList.add(user);
}
cursor.close();
db.close();
return userList;
}
```
以上是一个简单的示例,实际项目中需要根据具体需求进行修改和完善。
阅读全文