Android studio SQlite增删改查数据库
时间: 2024-05-10 22:13:42 浏览: 143
android sqllite 增删改查
好的,您可以参考以下示例代码进行操作。
首先,在Android Studio中创建一个新项目。在项目的 build.gradle 文件中添加以下依赖项:
```gradle
dependencies {
...
implementation 'androidx.sqlite:sqlite:2.1.0'
}
```
接下来,创建一个 DBHelper 类来管理数据库的创建和升级。以下是一个示例实现:
```java
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "myTable";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_AGE = "age";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_AGE + " INTEGER)";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Handle database upgrade
}
}
```
该类定义了一个名为 myTable 的表,包含 id、name 和 age 列。在 onCreate() 方法中,它会创建该表。
现在,您可以在您的 Activity 或 Fragment 中使用 DBHelper 类执行 SQLite 操作了。以下是添加、更新、查询和删除操作的示例实现:
```java
public class MainActivity extends AppCompatActivity {
private DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this);
// Insert a record
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_NAME, "John");
values.put(DBHelper.COLUMN_AGE, 25);
db.insert(DBHelper.TABLE_NAME, null, values);
// Update a record
values.put(DBHelper.COLUMN_AGE, 26);
db.update(DBHelper.TABLE_NAME, values, DBHelper.COLUMN_NAME + "=?", new String[]{"John"});
// Query records
Cursor cursor = db.query(DBHelper.TABLE_NAME, null, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME));
int age = cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_AGE));
Log.d("MainActivity", "id: " + id + ", name: " + name + ", age: " + age);
}
cursor.close();
// Delete a record
db.delete(DBHelper.TABLE_NAME, DBHelper.COLUMN_NAME + "=?", new String[]{"John"});
}
@Override
protected void onDestroy() {
dbHelper.close();
super.onDestroy();
}
}
```
在 onCreate() 方法中,它打开并获取一个可写的 SQLiteDatabase 对象,向 myTable 表中插入一个名为 John、年龄为 25 的记录,然后更新 John 的年龄为 26,接着查询 myTable 表中的记录并打印出来,最后删除名为 John 的记录。在 onDestroy() 方法中关闭 DBHelper 对象。
阅读全文