实现SQLite数据库的创建、增删改查操作并实现SharedPreferences存储数据
时间: 2024-03-05 07:51:00 浏览: 70
好的,我来回答你的问题。首先,关于SQLite数据库的操作,可以使用Android提供的SQLiteOpenHelper类来完成。代码示例如下:
创建数据库:
```java
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "mydb.db";
private static final int DB_VERSION = 1;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS user (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 数据库升级时调用
}
}
```
插入数据:
```java
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "Tom");
values.put("age", 20);
db.insert("user", null, values);
db.close();
```
查询数据:
```java
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query("user", null, 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"));
Log.d("TAG", "id=" + id + ", name=" + name + ", age=" + age);
}
cursor.close();
db.close();
```
更新数据:
```java
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "Jerry");
values.put("age", 22);
db.update("user", values, "_id=?", new String[]{"1"});
db.close();
```
删除数据:
```java
DBHelper dbHelper = new DBHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("user", "_id=?", new String[]{"1"});
db.close();
```
关于SharedPreferences的使用,可以通过以下代码实现:
写入数据:
```java
SharedPreferences sp = context.getSharedPreferences("my_sp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("name", "Tom");
editor.putInt("age", 20);
editor.commit();
```
读取数据:
```java
SharedPreferences sp = context.getSharedPreferences("my_sp", Context.MODE_PRIVATE);
String name = sp.getString("name", "");
int age = sp.getInt("age", 0);
Log.d("TAG", "name=" + name + ", age=" + age);
```
以上就是SQLite数据库和SharedPreferences的基本使用方法,希望能对你有所帮助。
阅读全文