在Android Studio中使用Java实现对SQLite数据库的增删改查操作,可以通过SQLiteOpenHelper
类来创建和管理数据库,并使用SQLiteDatabase
对象进行具体的数据操作。以下是一个简单的例子:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper 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 COL_1 = "ID";
private static final String COL_2 = "NAME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_2 + " TEXT)";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
// 插入数据
public boolean insertData(String itemName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, itemName);
long result = db.insert(TABLE_NAME, null, contentValues);
return result != -1;
}
// 更新数据
public boolean updateData(int id, String itemName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, itemName);
int result = db.update(TABLE_NAME, contentValues, COL_1 + "=?", new String[]{Integer.toString(id)});
return result > 0;
}
// 删除数据
public boolean deleteData(int id) {
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete(TABLE_NAME, COL_1 + "=?", new String[]{Integer.toString(id)});
return result > 0;
}
// 查询数据
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_NAME, new String[]{COL_1, COL_2}, null, null, null, null, null);
}
}
使用时,首先需要创建DatabaseHelper
的实例,然后通过这个实例进行增删改查操作。例如:
DatabaseHelper dbHelper =