基于AndroidStudio内置数据库SQLite,构建简单实现数据库增删改查功能APP
以下是一个简单的数据库操作示例,包括增删改查功能:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TABLE_NAME = "my_table";
private static final String COL_1 = "ID";
private static final String COL_2 = "NAME";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + TABLE_NAME + " (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_2 + " TEXT)";
db.execSQL(createTableStatement);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, item);
long result = db.insert(TABLE_NAME, null, contentValues);
return result != -1;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return res;
}
public boolean updateData(String id, String newName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, newName);
int result = db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{id});
return result > 0;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete(TABLE_NAME, "ID = ?", new String[]{id});
return result;
}
}
在Activity中使用这个帮助类:
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(this);
// 插入数据
db.insertData("Sample Item");
// 查询数据
评论已关闭