在Android中实现SQLite数据库操作通常涉及以下几个步骤:创建数据库助手类、定义数据库表结构、执行SQL查询和更新操作等。以下是一个基本的实现指南:
1. 添加依赖
在Android项目中,SQLite是内置支持的,因此不需要额外添加依赖。如果你使用的是较新的Android架构组件,可以考虑使用Room持久化库,它是对SQLite的一个抽象层,但这里我们直接使用SQLite。
2. 创建数据库助手类
首先,你需要创建一个继承自SQLiteOpenHelper
的类。这个类将帮助你管理数据库的创建和版本管理。
java复制代码
|---|---------------------------------------------------------------------------------------|
| | import android.content.Context;
|
| | import android.database.sqlite.SQLiteDatabase;
|
| | import android.database.sqlite.SQLiteOpenHelper;
|
| | |
| | public class MyDatabaseHelper extends SQLiteOpenHelper {
|
| | |
| | // Database Version
|
| | private static final int DATABASE_VERSION = 1;
|
| | |
| | // Database Name
|
| | private static final String DATABASE_NAME = "MyDatabase.db";
|
| | |
| | // Table Name
|
| | private static final String TABLE_NAME = "user_table";
|
| | |
| | // Table Columns
|
| | private static final String COL1 = "ID";
|
| | private static final String COL2 = "NAME";
|
| | private static final String COL3 = "EMAIL";
|
| | |
| | // Create Table SQL Statement
|
| | private static final String CREATE_TABLE =
|
| | "CREATE TABLE " + TABLE_NAME + " (" +
|
| | COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
|
| | COL2 + " TEXT, " +
|
| | COL3 + " TEXT);";
|
| | |
| | // Constructor
|
| | public MyDatabaseHelper(Context context) {
|
| | super(context, DATABASE_NAME, null, DATABASE_VERSION);
|
| | }
|
| | |
| | // onCreate: This method is called when the database is created for the first time.
|
| | @Override
|
| | public void onCreate(SQLiteDatabase db) {
|
| | db.execSQL(CREATE_TABLE);
|
| | }
|
| | |
| | // onUpgrade: This method is called when the database needs to be upgraded.
|
| | @Override
|
| | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
|
| | db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
|
| | onCreate(db);
|
| | }
|
| | }
|
3. 插入数据
你可以通过创建一个新的方法,在MyDatabaseHelper
类或者在Activity/Fragment中调用数据库助手类的方法来插入数据。
java复制代码
|---|------------------------------------------------------------------|
| | import android.content.ContentValues;
|
| | import android.database.sqlite.SQLiteDatabase;
|
| | import android.widget.Toast;
|
| | |
| | // 插入数据的方法
|
| | public long insertData(String name, String email) {
|
| | SQLiteDatabase db = this.getWritableDatabase();
|
| | |
| | ContentValues contentValues = new ContentValues();
|
| | contentValues.put(COL2, name);
|
| | contentValues.put(COL3, email);
|
| | |
| | long result = db.insert(TABLE_NAME, null, contentValues);
|
| | |
| | // 如果插入成功,返回新行的ID,否则返回-1
|
| | if (result == -1) {
|
| | Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
|
| | } else {
|
| | Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
|
| | }
|
| | |
| | return result;
|
| | }
|
4. 查询数据
同样地,你可以创建一个方法来查询数据。
java复制代码
|---|-------------------------------------------------------------------------------------------------------|
| | import android.database.Cursor;
|
| | import android.database.sqlite.SQLiteDatabase;
|
| | import java.util.ArrayList;
|
| | import java.util.List;
|
| | |
| | // User类,用于存储用户数据
|
| | public class User {
|
| | private int id;
|
| | private String name;
|
| | private String email;
|
| | |
| | // Getters and Setters
|
| | // ...
|
| | }
|
| | |
| | // 查询所有数据的方法
|
| | public List<User> getAllData() {
|
| | List<User> userList = new ArrayList<>();
|
| | |
| | SQLiteDatabase db = this.getReadableDatabase();
|
| | Cursor cursor = db.query(TABLE_NAME, new String[]{COL1, COL2, COL3}, null, null, null, null, null);
|
| | |
| | while (cursor.moveToNext()) {
|
| | int id = cursor.getInt(cursor.getColumnIndexOrThrow(COL1));
|
| | String name = cursor.getString(cursor.getColumnIndexOrThrow(COL2));
|
| | String email = cursor.getString(cursor.getColumnIndexOrThrow(COL3));
|
| | |
| | User user = new User(id, name, email);
|
| | userList.add(user);
|
| | }
|
| | |
| | cursor.close();
|
| | return userList;
|
| | }
|
5. 更新和删除数据
类似地,你可以创建方法来更新和删除数据。
java复制代码
|---|-------------------------------------------------------------------------------------|
| | // 更新数据的方法
|
| | public int updateData(int id, String name, String email) {
|
| | SQLiteDatabase db = this.getWritableDatabase();
|
| | |
| | ContentValues contentValues = new ContentValues();
|
| | contentValues.put(COL2, name);
|
| | contentValues.put(COL3, email);
|
| | |
| | String selection = COL1 + " = ?";
|
| | String[] selectionArgs = { String.valueOf(id) };
|
| | |
| | int rowsUpdated = db.update(TABLE_NAME, contentValues, selection, selectionArgs);
|
| | return rowsUpdated;
|
| | }
|
| | |
| | // 删除数据的方法
|
| | public void deleteData(int id) {
|
| | SQLiteDatabase db = this.getWritableDatabase();
|
| | |
| | String selection = COL1 + " = ?";
|
| | String[] selectionArgs = { String.valueOf(id) };
|
| | |
| | db.delete(TABLE_NAME, selection, selectionArgs);
|
| | }
|
6. 使用数据库助手类
最后,在你的Activity或Fragment中实例化并使用这个数据库助手类。
java复制代码
|---|----------------------------------------------------------------------------|
| | public class MainActivity extends AppCompatActivity {
|
| | |
| | MyDatabaseHelper dbHelper;
|
| | |
| | @Override
|
| | protected void onCreate(Bundle savedInstanceState) {
|
| | super.onCreate(savedInstanceState);
|
| | setContentView(R.layout.activity_main);
|
| | |
| | dbHelper = new MyDatabaseHelper(this);
|
| | |
| | // 插入数据
|
| | long newRowId = dbHelper.insertData("John Doe", "[email protected]");
|
| | |
| | // 查询数据
|
| | List<User> users = dbHelper.getAllData();
|
| | |
| | // 更新数据
|
| | dbHelper.updateData((int) newRowId, "Jane Doe", "[email protected]");
|
| | |
| | // 删除数据
|
| | dbHelper.deleteData((int) newRowId);
|
| | }
|
| | }
|
通过以上步骤,你可以在Android应用中实现基本的SQLite数据库操作。对于更复杂的应用,可以考虑使用Room持久化库来简化数据库操作。