android 动态更新sql

本文介绍了一种不需版本更新即可更新数据库的方法,通过下载SQL文件并在线执行,实现数据库的高效升级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们做项目是会遇到需要更新数据库,但是又不想发版本的情况,

这时可以从服务器下载sql文件,然后依次执行


1 ,downLoadFile


2,读取文件流,然后执行sql语句

                                File LocalFile = new File(sqlfilepath);
if (LocalFile.exists()) {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(LocalFile), "utf-8");
int c;
StringBuffer sb = new StringBuffer();
char buffer[] = new char[1024];
while ((c = reader.read(buffer, 0, 1024)) != -1) {
sb.append(new String(buffer, 0, c));
}
String sqlStr = sb.toString();
sqlStr = sqlStr.replaceAll("\r\n", "");
String[] sqlStrs = sqlStr.split(";");
for (String sql : sqlStrs) {
getDbUtils().execNonQuery(sql);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}


3 another

 

/**
 * This reads a file from the given Resource-Id and calls every line of it as a SQL-Statement
 * 
 * @param context
 *  
 * @param resourceId
 *  e.g. R.raw.food_db
 * 
 * @return Number of SQL-Statements run
 * @throws IOException
 */
public int insertFromFile(Context context, int resourceId) throws IOException {
    // Reseting Counter
    int result = 0;

    // Open the resource
    InputStream insertsStream = context.getResources().openRawResource(resourceId);
    BufferedReader insertReader = new BufferedReader(new InputStreamReader(insertsStream));

    // Iterate through lines (assuming each insert has its own line and theres no other stuff)
    while (insertReader.ready()) {
        String insertStmt = insertReader.readLine();
        db.execSQL(insertStmt);
        result++;
    }
    insertReader.close();

    // returning number of inserted rows
    return result;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Android西红柿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值