新版android studio如何连接数据库
时间: 2023-11-21 16:55:50 浏览: 83
在新版Android Studio中连接SQLite数据库的步骤如下:
1.在项目的build.gradle文件中添加以下依赖项:
```gradle
dependencies {
implementation 'androidx.sqlite:sqlite:2.1.0'
}
```
2.在Java代码中创建SQLiteOpenHelper类,该类将帮助您创建和管理数据库。以下是一个示例:
```java
public class MyDatabaseHelper extends SQLiteOpenHelper {
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);
}
@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);
}
}
```
3.在您的Activity或Fragment中,创建MyDatabaseHelper对象并获取可写数据库实例:
```java
MyDatabaseHelper dbHelper = new MyDatabaseHelper(getContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
```
4.现在您可以使用SQLiteDatabase对象执行SQL查询和更新。以下是一个示例:
```java
// 插入数据
ContentValues values = new ContentValues();
values.put("name", "John");
values.put("age", 30);
db.insert("mytable", null, values);
// 查询数据
Cursor cursor = db.query("mytable", 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("MyApp", "id: " + id + ", name: " + name + ", age: " + age);
}
// 更新数据
ContentValues values = new ContentValues();
values.put("age", 31);
db.update("mytable", values, "name = ?", new String[]{"John"});
// 删除数据
db.delete("mytable", "name = ?", new String[]{"John"});
```
阅读全文