// 建表時加入唯一索引
CREATE TABLE contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT UNIQUE, -- 唯一約束
name TEXT,
phone TEXT
);
// 插入時用 INSERT OR REPLACE (或 ON CONFLICT REPLACE)
INSERT OR REPLACE INTO contacts (user_id, name, phone) VALUES (?, ?, ?);
效果:user_id 存在則更新該行,不存在則插入新行。
// 查詢是否存在
Cursor c = db.query("contacts", new String[]{"id"}, "user_id=?", new String[]{userId}, null, null, null);
if (c.getCount() == 0) {
// 插入
} else {
// 更新或忽略
}
c.close();
INSERT INTO contacts (user_id, name, phone) VALUES (?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET name=excluded.name, phone=excluded.phone;
UNIQUE 索引自動建立索引,查詢效能也不受影響created_at 欄位