更新数据库Android

时间:2010-01-19 22:29:58

标签: android

谁能告诉我如何在android中更新数据库。我用嵌入式数据库创建了一个应用程序。我更改了清单中的数据库版本并创建了更新方法。我想测试它以查看数据库是否正确更新但是当我使用adb命令时,只有-r将允许我重新安装但它保留数据库。有没有办法运行允许我更新数据库的adb命令。感谢。

6 个答案:

答案 0 :(得分:7)

以下是我将如何处理updateRow方法:

public void updateRow(long rowId, String code, String name) {
      ContentValues args = new ContentValues();
      args.put("code", code);
      args.put("name", name);
      db.update(DATABASE_TABLE, args, "_id=" + rowId, null);
}

答案 1 :(得分:3)

对我有用的是更改数据库的版本号。这是内容提供程序的onCreate()方法使用的常量数。如果您不为数据库使用内容提供程序,并直接查询它,则类似的东西会起作用。请参阅源代码示例here

答案 2 :(得分:2)

答案 3 :(得分:1)

对我来说有用的是更改我提供给DBOpenHelper类的版本号参数,该类扩展了SQLiteOpenHelper(用于创建/读取/写入/等等... Android数据库的类)。当版本号参数递增时,对该参数的新值调用onUpdate()函数一次。

答案 4 :(得分:1)

如果通过更新意味着重建(就像我在开发期间那样,每次我的应用程序启动时都想从一个新数据库开始),那么在访问应用程序中的数据库之前添加此代码:

this.getContext().getApplicationContext().deleteDatabase(DATABASENAME);

找到数据库的路径:

SQLiteHelper sql_database_helper = new SQLiteHelper(this.getContext().getApplicationContext());
File dbFile = getDatabasePath(DATABASENAME);
Log.v("XIX","DB FILE PATH:"+dbFile.getAbsolutePath());

然后从命令提示符处删除您的数据库:

> adb devices
List of devices attached
3246%$%^$&17   device  
> adb shell
$ su 
su
rm mydatapath

注意:您可能无法在不破解手机的情况下访问su命令

说明: 如果您不想遵循r1k0给出的建议(如果您正在升级已发布的应用程序,这可能是正确的方法)那么您可以使用以下adb命令删除数据库并重新启动应用程序将再次调用onCreate方法。

答案 5 :(得分:1)

我不建议用这种方式:

public void updateRow(long rowId, String code, String name) {
      ContentValues args = new ContentValues();
      args.put("code", code);
      args.put("name", name);
      db.update(DATABASE_TABLE, args, "_id=" + rowId, null);
}

你的应用程序很容易受到sql注入攻击,最好的方法就是这样:

public void updateRow(long rowId, String code, String name) {
      ContentValues args = new ContentValues();
      args.put("code", code);
      args.put("name", name);
      String whereArgs[] = new String[1];
      whereArgs[0] = "" + rowId;
      db.update(DATABASE_TABLE, args, "_id= ?", whereArgs);
}