java Android SQLite - SQLiteDatabase.replace() 实际上是做什么的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7984280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:33:45  来源:igfitidea点击:

Android SQLite - what does SQLiteDatabase.replace() actually do?

javaandroidsqlite

提问by Jake Wilson

I need to do a INSERT or UPDATE IF EXIST type of procedure with my database. I read that .replace()was the way to go. It inserts new records just fine, but if the record already exists, it doesn't appear to update it.

我需要对我的数据库执行 INSERT 或 UPDATE IF EXIST 类型的过程。我读到那.replace()是要走的路。它插入新记录就好了,但如果记录已经存在,它似乎不会更新它。

I have something like this:

我有这样的事情:

ContentValues values = new ContentValues();
values.put(ID, 1);
values.put(NAME, "bob");
values.put(VISIBLE, true);
db.replace("peopleTable", null, values);

If I run this code when this record isn't in the database, it appears to create the record just fine, as if I did an insert(). But if I change NAME to "john" or something like that, and run the replace()again, it doesn't appear to update the record.

如果我在此记录不在数据库中时运行此代码,它似乎可以很好地创建记录,就像我在insert(). 但是,如果我将 NAME 更改为“john”或类似的内容,然后replace()再次运行,它似乎不会更新记录。

According to the docs, here is the syntax:

根据文档,这里是语法:

public long replace (String table, String nullColumnHack, ContentValues initialValues)

Why is it called initalValues? Does that mean those values are only used when the record doesn't exist and it's going to be inserted? If so, how do you use the method to update a record? Where do you specify the new values?

为什么叫它initalValues?这是否意味着这些值仅在记录不存在且将被插入时使用?如果是这样,您如何使用该方法更新记录?您在哪里指定新值?

If I am misunderstanding what replace()does altogether, can someone explain what it's purpose is?

如果我replace()完全误解了什么,有人可以解释它的目的是什么吗?

采纳答案by Jeff Gilfelt

As I understand it replace()works much like the SQLite REPLACEkeyword - a row will be updated if a unique constraint violation occurs for the insert. So the ID column in your example would need to have a PRIMARY KEY constraint in the database schema for the row to be updated.

据我了解,它的replace()工作方式与 SQLite REPLACE关键字非常相似- 如果插入发生唯一约束违规,则将更新一行。因此,您的示例中的 ID 列需要在数据库架构中具有 PRIMARY KEY 约束才能更新行。

回答by tarn

The replace() method actually execute the sql command insert or replace into (...) values (...)

replace() 方法实际执行sql命令 insert or replace into (...) values (...)