开发者

How to use INSERT OR REPLACE correctly?

I was originally looking for an INSERT OR UPDATE ability in SQLite but searches showed similar question askers being pointed to using INSERT OR REPLACE.

I'm obviously misunderstanding how this works and obviously I can't use WHERE as I'm getting the following SQLiteException...

08-12 01:38:22.973: ERROR/AndroidRuntime(29242): FATAL EXCEPTION: main
08-12 01:38:22.973: ERROR/AndroidRuntime(29242): android.database.sqlite.SQLiteException:
                        near "WHERE":
                            syntax error: 
                                INSERT OR REPLACE INTO SERVERS (
                                    server_name,
                                    service_uri_mobile,
               开发者_运维知识库                     service_uri_wifi,
                                    valid_ssids,
                                    username,password
                                ) VALUES (
                                    'Default',
                                    'http://myserver.com:8790/',
                                    'http://192.168.1.1:8790/',
                                    '[]',
                                    'admin',
                                    'password')
                                WHERE server_name='Default'

The SQL string I'm using is as follows...

String UpdateString = "INSERT OR REPLACE INTO SERVERS " +
    "(server_name,service_uri_mobile,service_uri_wifi,valid_ssids,username,password) VALUES ('" +
    locater.getServerName() + "','" +
    locater.getServiceUriMobile().toString() + "','" +
    locater.getServiceUriWifi().toString() + "','" +
    locater.getValidSsids().toString() + "','" +
    locater.getUsername() + "','" +
    locater.getPassword() + "') " +
    "WHERE server_name='" + locater.getServerName() + "'";

I've looked at this page explaining REPLACE but don't quite understand it. How would I re-write the above SQLite command and have it only try to replace the record where the server_name matches (i.e., the equivalent of a WHERE clause)?


Looking at the documentation (and mirroring the comments below the question), REPLACE should be used when UPDATEing (or in other words changing) columns that are UNIQUE. To wit:

REPLACE

When a UNIQUE constraint violation occurs, the REPLACE algorithm deletes pre-existing rows that are causing the constraint violation prior to inserting or updating the current row and the command continues executing normally.

http://sqlite.org/lang_conflict.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜