android实现向Sqlite数据库中增加、删除、查询数据实训代码
时间: 2024-02-03 08:03:48 浏览: 139
以下是一个简单的 Android 应用程序,它使用 SQLite 数据库来存储和检索数据。这个应用程序允许用户添加、删除和查询数据。
首先,在 `AndroidManifest.xml` 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
然后在 `build.gradle` 文件中添加以下依赖:
```groovy
implementation 'androidx.sqlite:sqlite:2.1.0'
```
接下来,创建一个名为 `DatabaseHelper` 的类来管理数据库。这个类继承自 `SQLiteOpenHelper` 类,它有两个方法:`onCreate()` 和 `onUpgrade()`,可以在这里创建和更新数据库。
```java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(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);
}
}
```
在 `onCreate()` 方法中,我们创建一个名为 `mytable` 的表,它有三个列:`_id`、`name` 和 `age`。`_id` 列是一个自增的整数,用作主键。`name` 和 `age` 列是分别用于存储名称和年龄的文本和整数列。
在 `onUpgrade()` 方法中,我们删除旧表并创建新表。
接下来,创建一个名为 `MainActivity` 的类来管理应用程序。这个类包含三个方法:`addData()`、`deleteData()` 和 `queryData()`,它们分别用于添加、删除和查询数据。
```java
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText mNameEditText;
private EditText mAgeEditText;
private TextView mDataTextView;
private SQLiteDatabase mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNameEditText = findViewById(R.id.name_edit_text);
mAgeEditText = findViewById(R.id.age_edit_text);
mDataTextView = findViewById(R.id.data_text_view);
DatabaseHelper dbHelper = new DatabaseHelper(this);
mDatabase = dbHelper.getWritableDatabase();
}
public void addData(View view) {
String name = mNameEditText.getText().toString().trim();
String ageString = mAgeEditText.getText().toString().trim();
if (name.isEmpty() || ageString.isEmpty()) {
Toast.makeText(this, "Please enter a name and age", Toast.LENGTH_SHORT).show();
return;
}
int age = Integer.parseInt(ageString);
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("age", age);
long result = mDatabase.insert("mytable", null, cv);
if (result == -1) {
Toast.makeText(this, "Failed to add data", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Data added successfully", Toast.LENGTH_SHORT).show();
}
}
public void deleteData(View view) {
String name = mNameEditText.getText().toString().trim();
if (name.isEmpty()) {
Toast.makeText(this, "Please enter a name", Toast.LENGTH_SHORT).show();
return;
}
int result = mDatabase.delete("mytable", "name=?", new String[]{name});
if (result == 0) {
Toast.makeText(this, "No data found to delete", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Data deleted successfully", Toast.LENGTH_SHORT).show();
}
}
public void queryData(View view) {
Cursor cursor = mDatabase.query("mytable", null, null, null, null, null, null);
StringBuilder sb = new StringBuilder();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
sb.append(id).append(": ").append(name).append(", ").append(age).append("\n");
}
if (sb.length() == 0) {
mDataTextView.setText("No data found");
} else {
mDataTextView.setText(sb.toString());
}
}
}
```
在 `onCreate()` 方法中,我们获取到 `EditText` 和 `TextView` 的实例,然后创建一个 `DatabaseHelper` 对象并获取到可写的 `SQLiteDatabase` 对象。
在 `addData()` 方法中,我们从 `EditText` 中获取名称和年龄,并将它们添加到 `ContentValues` 对象中。然后我们使用 `insert()` 方法将数据添加到数据库中,并根据结果显示适当的消息。
在 `deleteData()` 方法中,我们从 `EditText` 中获取名称,并使用 `delete()` 方法从数据库中删除对应的数据。然后我们根据结果显示适当的消息。
在 `queryData()` 方法中,我们使用 `query()` 方法从数据库中检索所有数据,并将它们显示在 `TextView` 中。
最后,我们需要在布局文件 `activity_main.xml` 中添加以下代码:
```xml
<EditText
android:id="@+id/name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name" />
<EditText
android:id="@+id/age_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Age" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Data"
android:onClick="addData" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Delete Data"
android:onClick="deleteData" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Query Data"
android:onClick="queryData" />
<TextView
android:id="@+id/data_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
```
这样,我们就完成了一个简单的 Android 应用程序,它可以使用 SQLite 数据库来存储和检索数据。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)