android - Android 应用程序中是否使用了数据库?
问题描述
了解如何在 Android 应用中使用数据库。
我想了解如何将 SQL 数据库连接到 Android 应用程序。它就像 YouTube 和更多使用数据库的应用程序。
请帮我谈谈在 Android 应用程序中使用数据库。
谢谢大家
解决方案
您可以使用android sqlite 数据库
以及更多信息SQLiteDatabase,
使用此代码连接到数据库
public class DBHelper extends SQLiteOpenHelper
{
private static String DB_NAME = "DataBase.sqlite";
private static String DB_PATH = "";
private static final int DB_VERSION = 63;
private SQLiteDatabase mDataBase;
private final Context mContext;
private boolean mNeedUpdate = false;
public DBHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
this.mContext = context;
DB_PATH = mContext.getApplicationInfo().dataDir + "/databases/";
boolean dbexist = checkDataBase();
if (dbexist)
{
openDataBase();
}
else
{
createDataBase();
}
}
private void createDataBase()
{
boolean dbexist = checkDataBase();
if (!dbexist)
{
this.getReadableDatabase();
this.close();
try
{
copyDataBase();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private boolean checkDataBase()
{
boolean checkdb = false;
try
{
String myPath = DB_PATH + DB_NAME;
File dbfile = new File(myPath);
checkdb = dbfile.exists();
}
catch (SQLiteException e)
{
e.printStackTrace();
}
return checkdb;
}
private void copyDataBase() throws IOException
{
InputStream myinput = mContext.getAssets().open("G2DcfxJZdu/" + DB_NAME);
OutputStream myoutput = new FileOutputStream(DB_PATH + DB_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = myinput.read(buffer)) > 0)
{
myoutput.write(buffer, 0, length);
}
myoutput.flush();
myoutput.close();
myinput.close();
}
private void openDataBase() throws SQLException
{
String mypath = DB_PATH + DB_NAME;
mDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close()
{
if (mDataBase != null)
{
mDataBase.close();
}
super.close();
}
@Override
public void onCreate(SQLiteDatabase db)
{
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
if (newVersion > oldVersion)
{
mNeedUpdate = true;
try
{
updateDataBase();
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}
private void updateDataBase() throws IOException
{
if (mNeedUpdate)
{
File dbFile = new File(DB_PATH + DB_NAME);
if (dbFile.exists())
{
dbFile.delete();
}
copyDataBase();
mNeedUpdate = false;
}
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
db.disableWriteAheadLogging();
}
推荐阅读
- sql - 我的 PLSQL 触发器没有在表中循环
- php - 图片正在上传到文件夹但未显示 - php上传图片
- blockchain - Corda:管理员可以看到 Corda 网络中的交易吗?
- git - 如何在不添加分支的完整提交历史记录的情况下合并来自另一个仓库的分支?
- android - Android:当应用程序在后台时,有什么方法可以从显着运动传感器收集数据?
- c# - 有没有更简单的方法来进行这个查询?
- powershell - 在詹金斯中将密码绑定传递给PowerShell脚本时遇到问题
- sql - 旋转多个属性并将它们分组为“单个”属性(多对一)
- php - PHP获取星期几的日期
- javascript - axios 拦截器:自定义标头仅添加到 OPTIONS 请求中