上一篇
安卓开发数据库保存到本地文件
- 行业动态
- 2025-04-22
- 6
SQLite数据库本地存储实现
创建数据库帮助类
public class DBHelper extends SQLiteOpenHelper { private static final String DB_NAME = "app_data.db"; // 数据库文件名 private static final int VERSION = 1; public DBHelper(Context context) { super(context, DB_NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 创建表结构 db.execSQL("CREATE TABLE users(id INTEGER PRIMARY KEY,name TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 数据库升级处理 } }
获取数据库文件路径
方法类型 | 路径获取方式 | 适用场景 |
---|---|---|
内部存储 | context.getDatabasePath(DB_NAME).getPath() |
默认推荐,应用卸载时自动清除 |
外部存储 | Environment.getExternalStorageDirectory() |
需要持久化数据,需申请WRITE_EXTERNAL_STORAGE权限 |
数据库操作示例
// 插入数据 SQLiteDatabase db = helper.getWritableDatabase(); db.execSQL("INSERT INTO users(name) VALUES(?)", new Object[]{"John"}); // 查询数据 Cursor cursor = db.rawQuery("SELECT FROM users", null); while(cursor.moveToNext()){ int id = cursor.getInt(0); String name = cursor.getString(1); }
数据库文件管理
备份数据库到SD卡
public void backupDatabase(Context context, File destFile) throws IOException { String sourcePath = context.getDatabasePath("app_data.db").getPath(); try(InputStream is = new FileInputStream(sourcePath); OutputStream os = new FileOutputStream(destFile)){ byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) > 0){ os.write(buffer,0,len); } } }
恢复数据库文件
public void restoreDatabase(Context context, File backupFile) throws IOException { String targetPath = context.getDatabasePath("app_data.db").getPath(); try(InputStream is = new FileInputStream(backupFile); OutputStream os = new FileOutputStream(targetPath, false)){ // 覆盖模式 byte[] buffer = new byte[1024]; int len; while((len = is.read(buffer)) > 0){ os.write(buffer,0,len); } } }
存储位置对比分析
存储类型 | 路径示例 | 生命周期 | 权限要求 | 适用场景 |
---|---|---|---|---|
应用私有目录 | /data/data/包名/databases/ | 与应用同生命周期 | 无特殊权限 | 常规本地存储 |
外部公共目录 | /storage/emulated/0/Download/ | 永久保留 | MANAGE_EXTERNAL_STORAGE(Android 11+) | 数据持久化备份 |
应用缓存目录 | /data/data/包名/cache/ | 可被系统清理 | 无 | 临时数据存储 |
常见问题与解答
Q1:如何在不同Android版本中申请外部存储权限?
A1:
- Android 10以下:在
AndroidManifest.xml
添加WRITE_EXTERNAL_STORAGE
权限 - Android 11+:需要声明
MANAGE_EXTERNAL_STORAGE
权限,并通过系统弹窗引导用户授权 - 推荐使用
MediaStore
API替代直接文件操作
Q2:如何加密本地数据库文件?
A2:
- 修改
SQLiteOpenHelper
构造方法:public DBHelper(Context context) { super(context, getEncryptedDBName(), null, VERSION); }
- 实现加密文件名生成:
private String getEncryptedDBName() { return "encrypted_" + Base64.encodeToString("app_data.db".getBytes(), Base64.DEFAULT) + ".db"; }
- 在数据库操作前进行解密:
// 解密逻辑(需集成加密库如SQLCipher)