Android studio项目能实现增删改查功能
时间: 2023-11-29 13:04:39 浏览: 125
是的,Android Studio项目可以实现增删改查功能。你可以使用SQLite数据库来存储数据,并使用Java代码来实现增删改查操作。这里是一个简单的示例:
1. 创建一个SQLite数据库和表格来存储数据。
```
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "mytable";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_AGE + " INTEGER)";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
```
2. 实现增删改查操作。
```
public class MyDAO {
private SQLiteDatabase db;
private DBHelper dbHelper;
public MyDAO(Context context) {
dbHelper = new DBHelper(context);
db = dbHelper.getWritableDatabase();
}
public void addData(String name, int age) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, name);
values.put(DBHelper.COLUMN_AGE, age);
db.insert(DBHelper.TABLE_NAME, null, values);
}
public void deleteData(int id) {
db.delete(DBHelper.TABLE_NAME, DBHelper.COLUMN_ID + "=?", new String[]{String.valueOf(id)});
}
public void updateData(int id, String name, int age) {
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, name);
values.put(DBHelper.COLUMN_AGE, age);
db.update(DBHelper.TABLE_NAME, values, DBHelper.COLUMN_ID + "=?", new String[]{String.valueOf(id)});
}
public List<MyData> getAllData() {
List<MyData> dataList = new ArrayList<>();
Cursor cursor = db.query(DBHelper.TABLE_NAME, null, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME));
int age = cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_AGE));
dataList.add(new MyData(id, name, age));
}
return dataList;
}
}
```
其中,MyData是一个简单的Java类,用于存储从数据库中读取的数据。
这只是一个简单的示例,实际实现中可能需要更多的代码和复杂的逻辑。
阅读全文