androidstudio增删改查代码
时间: 2023-07-07 13:26:30 浏览: 109
以下是 Android Studio 中使用 SQLite 数据库进行增删改查的示例代码:
1. 建立数据库帮助类
```java
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS mytable " +
"(id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"name TEXT, " +
"age INTEGER)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
```
2. 插入数据
```java
public void insertData(String name, int age) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
db.insert("mytable", null, values);
db.close();
}
```
3. 查询数据
```java
public ArrayList<String> queryData() {
ArrayList<String> data = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
String[] columns = {"id", "name", "age"};
Cursor cursor = db.query("mytable", columns, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
data.add(id + " " + name + " " + age);
}
cursor.close();
db.close();
return data;
}
```
4. 更新数据
```java
public void updateData(int id, String name, int age) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
db.update("mytable", values, "id=?", new String[]{String.valueOf(id)});
db.close();
}
```
5. 删除数据
```java
public void deleteData(int id) {
SQLiteDatabase db = getWritableDatabase();
db.delete("mytable", "id=?", new String[]{String.valueOf(id)});
db.close();
}
```
注意:以上代码仅为示例,实际使用时需要根据具体情况进行修改。
阅读全文