SQLite 怎么在Androidstudio中使用
时间: 2024-05-16 20:13:01 浏览: 148
在 Android Studio 中使用 SQLite,需要进行以下几个步骤:
1. 在 build.gradle 文件中添加 SQLite 依赖:
```
dependencies {
implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
}
```
2. 创建一个数据库帮助类,继承自 SQLiteAssetHelper 类:
```java
public class MyDatabaseHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
```
3. 在 Activity 中打开数据库,并进行相应的操作:
```java
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
// 插入数据
ContentValues values = new ContentValues();
values.put("name", "张三");
values.put("age", 20);
db.insert("user", null, values);
// 查询数据
Cursor cursor = db.query("user", 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(TAG, "name: " + name + ", age: " + age);
} while (cursor.moveToNext());
}
cursor.close();
// 关闭数据库
db.close();
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)