有时候为了需要,会将数据库保存到外部存储或者SD卡中(对于这种情况可以通过加密数据来避免数据被破解),比如一个应用支持多个数据,每个数据都需要有一个对应的数据库,并且数据库中的信息量特别大时,这显然更应该将数据库保存在外部存储或者SD卡中,因为RAM的大小是有限的;其次在写某些测试程序时将数据库保存在SD卡更方便查看数据库中的内容。
Android通过SQLiteOpenHelper创建数据库时默认是将数据库保存在'/data/data/应用程序名/databases'目录下的,只需要在继承SQLiteOpenHelper类的构造函数中传入数据库名称就可以了,但如果将数据库保存到指定的路径下面,都需要通过重写继承SQLiteOpenHelper类的构造函数中的context,因为:在阅读SQLiteOpenHelper.java的源码时会发现:创建数据库都是通过Context的openOrCreateDatabase方法实现的,如果我们需要在指定的路径下创建数据库,就需要写一个类继承Context,并复写其openOrCreateDatabase方法,在openOrCreateDatabase方法中指定数据库存储的路径即可,下面为类SQLiteOpenHelper中getWritableDatabase和getReadableDatabase方法的源码,SQLiteOpenHelper就是通过这两个方法来创建数据库的。
/** * Create and/or open a database that will be used for reading and writing. * The first time this is called, the database will be opened and * {@link #onCreate}, {@link #onUpgrade} and/or {@link #onOpen} will be * called. * * <p>Once opened successfully, the database is cached, so you can * call this method every time you need to write to the database. * (Make sure to call {@link #close} when you no longer need the database.) * Errors such as bad permissions or a full disk may cause this method * to fail, but future attempts may succeed if the problem is fixed.</p> * * <p class="caution">Database upgrade may take a long time, you * should not call this method from the application main thread, including * from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}. * * @throws SQLiteException if the database cannot be opened for writing * @return a read/write database object valid until {@link #close} is called */ public synchronized SQLiteDatabase getWritableDatabase() { if (mDatabase != null) { if (!mDatabase.isOpen()) { // darn! the user closed the database by calling mDatabase.close() mDatabase = null; } else if (!mDatabase.isReadOnly()) { return mDatabase; // The database is already open for business } } if (mIsInitializing) { throw new IllegalStateException("getWritableDatabase called recursively"); } // If we have a read-only database open, someone could be using it // (though they shouldn't), which would cause a lock to be held on // the file, and our attempts to open the database read-write would // fail waiting for the file lock. To prevent that, we acquire the // lock on the read-only database, which shuts out other users. boolean success = false; SQLiteDatabase db = null; if (mDatabase != null) mDatabase.lock(); try { mIsInitializing = true; if (mName == null) { db = SQLiteDatabase.create(null); } else { db = mContext.openOrCreateDatabase(mName, 0, mFactory, mErrorHandler); } int version = db.getVersion(); if (version != mNewVersion) { db.beginTransaction(); try { if (version == 0) { onCreate(db); } else { if (version > mNewVersion) { onDowngrade(db, version, mNewVersion); } else { onUpgrade(db, version, mNewVersion); } } db.setVersion(mNewVersion); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } onOpen(db); success = true; return db; } finally { mIsInitializing = false; if (success) { if (mDatabase != null) { try { mDatabase.close(); } catch (Exception e) { } mDatabase.unlock(); } mDatabase = db; } else { if (mDatabase != null) mDatabase.unlock(); if (db != null) db.close(); } } } /** * Create and/or open a database. This will be the same object returned by * {@link #getWritableDatabase} unless some problem, such as a full disk, * requires the database to be opened read-only. In that case, a read-only * database object will be returned. If the problem is fixed, a future call * to {@link #getWritableDatabase} may succeed, in which case the read-only * database object will be closed and the read/write object will be returned * in the future. * * <p class="caution">Like {@link #getWritableDatabase}, this method may * take a long time to return, so you should not call it from the * application main thread, including from * {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}. * * @throws SQLiteException if the database cannot be opened * @return a database object valid until {@link #getWritableDatabase} * or {@link #close} is called. */ public synchronized SQLiteDatabase getReadableDatabase() { if (mDatabase != null) { if (!mDatabase.isOpen()) { // darn! the user closed the database by calling mDatabase.close() mDatabase = null; } else { return mDatabase; // The database is already open for business } } if (mIsInitializing) { throw new IllegalStateException("getReadableDatabase called recursively"); } try { return getWritableDatabase(); } catch (SQLiteException e) { if (mName == null) throw e; // Can't open a temp database read-only! Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e); } SQLiteDatabase db = null; try { mIsInitializing = true; String path = mContext.getDatabasePath(mName).getPath(); db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY, mErrorHandler); if (db.getVersion() != mNewVersion) { throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to " + mNewVersion + ": " + path); } onOpen(db); Log.w(TAG, "Opened " + mName + " in read-only mode"); mDatabase = db; return mDatabase; } finally { mIsInitializing = false; if (db != null && db != mDatabase) db.close(); } }
通过上面的分析可以写出一个自定义的Context类,该类继承Context即可,但由于Context中有除了openOrCreateDatabase方法以外的其它抽象函数,所以建议使用非抽象类ContextWrapper,该类继承自Context,自定义的DatabaseContext类源码如下:
public class DatabaseContext extends ContextWrapper { public DatabaseContext(Context context){ super( context ); } /** * 获得数据库路径,如果不存在,则创建对象对象 * @param name * @param mode * @param factory */ @Override public File getDatabasePath(String name) { //判断是否存在sd卡 boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState()); if(!sdExist){//如果不存在, return null; }else{//如果存在 //获取sd卡路径 String dbDir= FileUtils.getFlashBPath(); dbDir += "DB";//数据库所在目录 String dbPath = dbDir+"/"+name;//数据库路径 //判断目录是否存在,不存在则创建该目录 File dirFile = new File(dbDir); if(!dirFile.exists()){ dirFile.mkdirs(); } //数据库文件是否创建成功 boolean isFileCreateSuccess = false; //判断文件是否存在,不存在则创建该文件 File dbFile = new File(dbPath); if(!dbFile.exists()){ try { isFileCreateSuccess = dbFile.createNewFile();//创建文件 } catch (IOException e) { e.printStackTrace(); } }else{ isFileCreateSuccess = true; } //返回数据库文件对象 if(isFileCreateSuccess){ return dbFile; }else{ return null; } } } /** * 重载这个方法,是用来打开SD卡上的数据库的,android 2.3及以下会调用这个方法。 * * @param name * @param mode * @param factory */ @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) { SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null); return result; } /** * Android 4.0会调用此方法获取数据库。 * * @see android.content.ContextWrapper#openOrCreateDatabase(java.lang.String, int, * android.database.sqlite.SQLiteDatabase.CursorFactory, * android.database.DatabaseErrorHandler) * @param name * @param mode * @param factory * @param errorHandler */ @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler) { SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null); return result; } }
在继承SQLiteOpenHelper的子类的构造函数中,用DatabaseContext的实例替代context即可:
DatabaseContext dbContext = new DatabaseContext(context); super(dbContext, mDatabaseName, null, VERSION);
基于Android如何实现将数据库保存到SD卡的全部内容就给大家介绍这么多,同时也非常感谢大家一直以来对小牛知识库网站的支持,谢谢。
目前,我的(使用的是Stackoverflow,我自己没有完整地编写)代码如下所示: 我得到错误:“打开失败;EACCES(权限被拒绝)”。 我的舱单是这样的:
问题内容: 我的Android手机上有一个数据库,我需要将信息保存到SD卡上。 是否可以将数据库文件以可读状态保存到SD卡上?我尚未找到有关如何执行此操作的任何信息。我知道数据库的名称,字段等… 我发现了一些示例,这些示例显示了如何保存到SD卡,但并不是我真正需要的。 将数据库文件复制到SD卡的某些源代码将是完美的。 希望这个问题很清楚。 问题答案: 是。这是我使用的功能: 对于我从事的项目,我在
本文向大家介绍pandas实现to_sql将DataFrame保存到数据库中,包括了pandas实现to_sql将DataFrame保存到数据库中的使用技巧和注意事项,需要的朋友参考一下 目的 在数据分析时,我们有中间结果,或者最终的结果,需要保存到数据库中;或者我们有一个中间的结果,如果放到数据库中通过sql操作会更加的直观,处理后再将结果读取到DataFrame中。这两个场景,就需要用到Dat
我一直在寻找保存音频到SdCard。 我还试图保存以下内容: 在这两种情况下,它都起作用,但会保存到内部存储中。从不使用SD卡 我使用getExternalFilesDirs()来创建。但如果用户卸载应用程序,则会丢失文件。 我不想那样。 如何将音频保存在SD卡公用文件夹中或创建新文件夹。 任何时候它都会创建到内部存储中。 有什么解决办法吗??? 我尝试了这个,我可以在SD卡中创建一个文档。还有一
我正在尝试开发一个小型电子商务项目。我有一个篮子和篮子项目实体。我只是想当我为客户保存购物篮时,我想把购物篮项目保存在数据库中。我认为我不应该为篮子项目创建存储库。我应该能够保存篮子项目,同时使用篮子存储库保存篮子。 在这里,我试图通过篮子服务获得一个篮子项目,并将其设置为篮子实体并保存它。 我有什么问题?我有个例外。
当我运行progressdialog出现在屏幕上时,它突然停止运行,并发出通知“应用程序停止了,再试一次”,然后我在android manitor上重复了这个错误,当然我首先要做的是:
我在使用JPA时遇到了一些困难。我没有得到任何异常,但我不能保存任何东西到数据库。我从Hibernate到Jpa,在那里一切都工作得很好。下面是我的文件 Application.Properties: 存储库: 服务: 我在提交表单时得到了200的响应,但在数据库中找不到数据
我有一个使用JPA的Spring Boot应用程序,它有两个数据源,一个用于DB2,一个用于SQL Server。 当我尝试将实体保存到SQL Server时,不会抛出任何错误,但该实体不会持久化到数据库。我看不到日志中正在生成插入。 提前感谢 下面是我尝试保存实体所执行的代码@组成部分 下面是sql Server配置。 这是SQL Server存储库 公共接口BeercupMessageLogR