Android:sqlite:删除记录

发布于 2025-02-12 07:44:53 字数 239 浏览 0 评论 0原文

我设法找到了Android开发团队未能提供的好例子。但是,我想询问删除是仅在主要活动中还是仅在DBHELPER中使用?我不确定dbhelper.java是否可能被称为dbadapter,因为一些示例似乎显示。我所指的特定语法是您可以使用Internet搜索找到的。但是,最近几个月 /几年中发现的许多示例没有很多,我不是专家:

db.rawquery(“从userDetails中select * name =?”,new String [] []

I managed to find good examples where the android development team failed to provide. However, I wish to ask if the delete can be used only in Main Activity or only in the DBHelper? I'm unsure if DBHelper.java might be called DBAdapter as some examples seem to show. The specific syntax I'm referring to is this which you can certainly find using an internet search. However, not many recent examples are available and many I found in the past months / years have too many files and I'm not an expert:

DB.rawQuery("Select * from Userdetails where name = ?", new String[]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莫多说 2025-02-19 07:44:53

但是,我想询问删除是否仅在主要活动中或仅在dbhelper中使用?

这两个都可以在这两个方面进行。

dbhelper's (dbadapter或您想称之为的任何东西)作业主要是为了提供控制数据库的手段,如果不存在,则创建它(在这种情况下调用了OnCreate 方法),还针对编码版本(调用Overdide Onupgrade方法,或在文件的标题中存储),或在更晦涩的环绕OnDewnGrade方法)。

从dbhelper中,您可以通过getWritabledatabasegetReadableDatabase方法获得SQLitedAtabase实例。您用来插入/删除/update/query的SQLitedAtabase对象。

SQLitedAtabase提供了采取访问操作的各种方法。例如execsql,RawQuery和许多便利方法,例如插入,更新,删除和查询。

便利方法可以简化问题,通常返回合适的可用值(例如,便利性插入方法返回一个长长的值,这是插入行的rowID的值,查询返回光标对象,即输出值)。

因此,您需要的只是一个sqlitedatabase对象。

示例

也许考虑以下示例,该示例通过dbhelper和mainactivty delete的行(尽管没有删除)。

数据库助手 ahelperforthedatabase

  • 命名与通常所看到的不同,只是表明该名称是无关紧要的。
  • 利用单例方法
  • 具有一种方法 deletebyid ,可以从类别中使用。

: -

class AHelperForTheDatabase extends SQLiteOpenHelper {

   public static final String DATABASE_NAME = "the_database.db";
   public static final int DATABASE_VERSION = 1;
   public static final String MYTABLE_TABLENAME = "mytable";
   public static final String MYTABLE_ID_COLUMN = BaseColumns._ID;
   public static final String MYTABLE_NAME_COLUMN = "_name";

   private static volatile AHelperForTheDatabase INSTANCE_OF_AHELPERFIRTHEDATABASE=null;


   private AHelperForTheDatabase(Context context) {
      super(context,DATABASE_NAME,null,DATABASE_VERSION);
   }

   public static AHelperForTheDatabase getInstanceOfAHelperForTheDatabase(Context context) {
      if (INSTANCE_OF_AHELPERFIRTHEDATABASE == null) {
         INSTANCE_OF_AHELPERFIRTHEDATABASE = new AHelperForTheDatabase(context);
      }
      return INSTANCE_OF_AHELPERFIRTHEDATABASE;
   }

   @Override
   public void onCreate(SQLiteDatabase db) {
      db.execSQL("CREATE TABLE IF NOT EXISTS " + MYTABLE_TABLENAME +
              "(" +
              MYTABLE_ID_COLUMN + " INTEGER PRIMARY KEY" +
              "," + MYTABLE_NAME_COLUMN + " TEXT " +
              ")" +
              "");
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int i, int i1) {}

   public long deleteById(long id) {
      // Convenience DELETE //
      return this.getWritableDatabase().delete(MYTABLE_TABLENAME,MYTABLE_ID_COLUMN + "=?",new String[]{String.valueOf(id)});
   }
}

MainAttivity ,其中包括4种不同的方式(请参阅注释)删除行(现在再次删除行,因为不存在): -

public class MainActivity extends AppCompatActivity {

    AHelperForTheDatabase TheDatabaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TheDatabaseHelper = AHelperForTheDatabase.getInstanceOfAHelperForTheDatabase(this);
        TheDatabaseHelper.deleteById(919191); /* DELETE via method defined as part of the Database Helper */
        /* DELETE via execSQL method nothing returned to indicate success or not */
        TheDatabaseHelper
                .getWritableDatabase()
                .execSQL(
                        "DELETE FROM "
                                + AHelperForTheDatabase.MYTABLE_TABLENAME
                                + " WHERE " + AHelperForTheDatabase.MYTABLE_ID_COLUMN + "=?",
                        new String[]{String.valueOf(919191)}
                );
        /* DELETE via delete convenience method - (can return number of affected rows) */
        TheDatabaseHelper
                .getWritableDatabase()
                .delete(
                        AHelperForTheDatabase.MYTABLE_TABLENAME,
                        AHelperForTheDatabase.MYTABLE_ID_COLUMN+"=?",
                        new String[]{String.valueOf(919191)}
                );
        /* DELETE via the rawQuery method (shouldn't really be used as does the additional of handling a Cursor for returning output data) */
        TheDatabaseHelper
                .getWritableDatabase()
                .rawQuery(
                        "DELETE FROM "
                                + AHelperForTheDatabase.MYTABLE_TABLENAME
                                + " WHERE " + AHelperForTheDatabase.MYTABLE_ID_COLUMN + "=?",
                        new String[]{String.valueOf(919191)}
                );
    }
}
  • 如此灵活性,显然您会来 在整个过程中,
  • 请注意,在所有情况下(尽管它在删除方便方法中隐藏了),实际值是 bound bound ,这是实际的SQL有一个 ,由值代替的, sqlite参数绑定。这被认为是 safe 为什么它可以保护

However, I wish to ask if the delete can be used only in Main Activity or only in the DBHelper?

Neither, it could be undertaken in either and even both.

The DBHelper's (DBAdapter or whatever you wish to call it) job is primarily to provide a means of controlled opening of the database, creating it if it doesn't exist (in which case the overidden onCreate method is called) and also checking the user_version (stored in the file's header) against a coded version (calling the overidden onUpgrade method, or in more obscure circumsyances the onDowngrade method).

From the DBHelper you can get an SQLiteDatabase instance via the getWritableDatabase or the getReadableDatabase methods. It is this SQliteDatabase object that you use to insert/delete/update/query.

The SQLitedatabase provides various methods of undertaking the access actions. Such as execSQL, rawQuery and many convenience methods such as insert, update, delete and query.

The convenience methods can simplify matters, often returning suitable usable values (e.g. the convenience insert method returns a long which is the value of the rowid of the inserted row, query returns a Cursor object which is the output values).

So all you require is an SQLiteDatabase object.

Example

Perhaps consider the following example, that DELETE's rows (albeit that there are none to delete) via both the DBHelper and via the MainActivty.

The Database Helper AHelperForTheDatabase

  • named different to what is typically seen, just to show that the name is irrelevant.
  • utilises a singleton approach
  • has an method deleteById that can be used from an instance the the class.

:-

class AHelperForTheDatabase extends SQLiteOpenHelper {

   public static final String DATABASE_NAME = "the_database.db";
   public static final int DATABASE_VERSION = 1;
   public static final String MYTABLE_TABLENAME = "mytable";
   public static final String MYTABLE_ID_COLUMN = BaseColumns._ID;
   public static final String MYTABLE_NAME_COLUMN = "_name";

   private static volatile AHelperForTheDatabase INSTANCE_OF_AHELPERFIRTHEDATABASE=null;


   private AHelperForTheDatabase(Context context) {
      super(context,DATABASE_NAME,null,DATABASE_VERSION);
   }

   public static AHelperForTheDatabase getInstanceOfAHelperForTheDatabase(Context context) {
      if (INSTANCE_OF_AHELPERFIRTHEDATABASE == null) {
         INSTANCE_OF_AHELPERFIRTHEDATABASE = new AHelperForTheDatabase(context);
      }
      return INSTANCE_OF_AHELPERFIRTHEDATABASE;
   }

   @Override
   public void onCreate(SQLiteDatabase db) {
      db.execSQL("CREATE TABLE IF NOT EXISTS " + MYTABLE_TABLENAME +
              "(" +
              MYTABLE_ID_COLUMN + " INTEGER PRIMARY KEY" +
              "," + MYTABLE_NAME_COLUMN + " TEXT " +
              ")" +
              "");
   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int i, int i1) {}

   public long deleteById(long id) {
      // Convenience DELETE //
      return this.getWritableDatabase().delete(MYTABLE_TABLENAME,MYTABLE_ID_COLUMN + "=?",new String[]{String.valueOf(id)});
   }
}

And MainActivity which includes 4 different ways (see comments) to delete rows (again now rows are actually delete as none exist) :-

public class MainActivity extends AppCompatActivity {

    AHelperForTheDatabase TheDatabaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TheDatabaseHelper = AHelperForTheDatabase.getInstanceOfAHelperForTheDatabase(this);
        TheDatabaseHelper.deleteById(919191); /* DELETE via method defined as part of the Database Helper */
        /* DELETE via execSQL method nothing returned to indicate success or not */
        TheDatabaseHelper
                .getWritableDatabase()
                .execSQL(
                        "DELETE FROM "
                                + AHelperForTheDatabase.MYTABLE_TABLENAME
                                + " WHERE " + AHelperForTheDatabase.MYTABLE_ID_COLUMN + "=?",
                        new String[]{String.valueOf(919191)}
                );
        /* DELETE via delete convenience method - (can return number of affected rows) */
        TheDatabaseHelper
                .getWritableDatabase()
                .delete(
                        AHelperForTheDatabase.MYTABLE_TABLENAME,
                        AHelperForTheDatabase.MYTABLE_ID_COLUMN+"=?",
                        new String[]{String.valueOf(919191)}
                );
        /* DELETE via the rawQuery method (shouldn't really be used as does the additional of handling a Cursor for returning output data) */
        TheDatabaseHelper
                .getWritableDatabase()
                .rawQuery(
                        "DELETE FROM "
                                + AHelperForTheDatabase.MYTABLE_TABLENAME
                                + " WHERE " + AHelperForTheDatabase.MYTABLE_ID_COLUMN + "=?",
                        new String[]{String.valueOf(919191)}
                );
    }
}
  • With such flexibility, you will obviously come across, the flexibility used in different ways.
  • Note that in ALL cases (albeit it hidden away in the delete convenience method) the actual value is bound that is the actual SQL has a ?, which is replaced by the value, by SQLite parameter binding. This is considered the safe why as it protects against SQL Injection.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文