android studio SQL数据存储
时间: 2023-12-11 09:33:44 浏览: 85
Android Studio中可以使用SQLiteOpenHelper类来实现SQLite数据存储。下面是一个简单的示例:
1. 创建一个继承自SQLiteOpenHelper的类,重写onCreate()和onUpgrade()方法:
```java
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "mydatabase.db";
private static final int DB_VERSION = 1;
public MyDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE mytable (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
```
2. 在需要使用数据库的Activity中,创建MyDatabaseHelper对象,并调用getWritableDatabase()方法获取可写的数据库对象:
```java
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
```
3. 使用SQLiteDatabase对象进行数据库操作,例如插入数据:
```java
ContentValues values = new ContentValues();
values.put("name", "张三");
values.put("age", 20);
db.insert("mytable", null, values);
```
4. 查询数据:
```java
Cursor cursor = db.query("mytable", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.d("MainActivity", "name: " + name + ", age: " + age);
} while (cursor.moveToNext());
}
cursor.close();
```
阅读全文