dbhelper类增删改查
时间: 2023-07-19 11:12:46 浏览: 101
DBHelper类是一个用于操作数据库的工具类,通常包括增删改查(CRUD)等数据库操作方法。下面是一个DBHelper类的增删改查示例:
```java
public class DBHelper extends SQLiteOpenHelper {
// 数据库名称
private static final String DB_NAME = "mydb.db";
// 数据库版本号
private static final int DB_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";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建表
String sql = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_AGE + " INTEGER)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升级表
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}
// 添加数据
public void insert(String name, int age) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_AGE, age);
db.insert(TABLE_NAME, null, values);
db.close();
}
// 删除数据
public void delete(int id) {
SQLiteDatabase db = getWritableDatabase();
String whereClause = COLUMN_ID + "=?";
String[] whereArgs = new String[]{String.valueOf(id)};
db.delete(TABLE_NAME, whereClause, whereArgs);
db.close();
}
// 修改数据
public void update(int id, String name, int age) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_AGE, age);
String whereClause = COLUMN_ID + "=?";
String[] whereArgs = new String[]{String.valueOf(id)};
db.update(TABLE_NAME, values, whereClause, whereArgs);
db.close();
}
// 查询数据
public List<Person> query() {
SQLiteDatabase db = getReadableDatabase();
List<Person> persons = new ArrayList<>();
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME));
int age = cursor.getInt(cursor.getColumnIndex(COLUMN_AGE));
Person person = new Person(id, name, age);
persons.add(person);
}
cursor.close();
db.close();
return persons;
}
}
```
上述代码实现了一个名为`mytable`的表的增删改查操作,其中`Person`是一个包含`id`、`name`和`age`属性的JavaBean类。你可以根据需要修改表名、列名和JavaBean类的属性。
阅读全文