dbhelper类增删改查
时间: 2023-07-19 18:46:10 浏览: 158
DBHelper类通常用于数据库的操作,包括增删改查等。以下是一个简单的DBHelper类的示例代码,可以实现基本的增删改查操作。
```java
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydb.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "mytable";
public static final String COL_ID = "id";
public static final String COL_NAME = "name";
public static final String COL_AGE = "age";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME +
"(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT, " +
COL_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 = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_NAME, name);
values.put(COL_AGE, age);
db.insert(TABLE_NAME, null, values);
db.close();
}
public void delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
String whereClause = COL_ID + " = ?";
String[] whereArgs = {String.valueOf(id)};
db.delete(TABLE_NAME, whereClause, whereArgs);
db.close();
}
public void update(int id, String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_NAME, name);
values.put(COL_AGE, age);
String whereClause = COL_ID + " = ?";
String[] whereArgs = {String.valueOf(id)};
db.update(TABLE_NAME, values, whereClause, whereArgs);
db.close();
}
public List<Person> query() {
List<Person> list = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = {COL_ID, COL_NAME, COL_AGE};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(COL_ID));
String name = cursor.getString(cursor.getColumnIndex(COL_NAME));
int age = cursor.getInt(cursor.getColumnIndex(COL_AGE));
Person person = new Person(id, name, age);
list.add(person);
}
cursor.close();
db.close();
return list;
}
}
```
其中,Person是一个简单的Java类,用于保存查询结果。
```java
public class Person {
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
使用DBHelper类进行增删改查操作的示例代码:
```java
DBHelper dbHelper = new DBHelper(context);
// 插入数据
dbHelper.insert("张三", 18);
// 删除数据
dbHelper.delete(1);
// 更新数据
dbHelper.update(2, "李四", 20);
// 查询数据
List<Person> list = dbHelper.query();
for (Person person : list) {
Log.d("DBHelper", person.getId() + " " + person.getName() + " " + person.getAge());
}
```
阅读全文