SQLite:防止重复 [英] SQLite: prevent duplicates

查看:292
本文介绍了SQLite:防止重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个表格来储存装置设定。该表有三行:id,parameter_name和parameter_value。



该表是通过执行以下查询语句创建的:

  DATABASE_CREATE =create table DATABASE_TABLE(KEY_ID INTEGER PRIMARY KEY AUTOINCREMENT,KEY_NAME INTEGER not null,VALUE TEXT not null); 

,然后通过执行以下方法存储行:

  private long insertRow(int rowParameter,String rowValue,SQLiteDatabase db){
long res = -1;
ContentValues settingsParameterValues = new ContentValues();
settingsParameterValues.put(KEY_NAME,rowParameter);
settingsParameterValues.put(VALUE,rowValue);
if(db!= null){
res = db.insert(DATABASE_TABLE,null,settingsParameterValues);
}
return res;
}

创建数据库时,存储默认值: / p>

  @Override 
public void onCreate(SQLiteDatabase db){
db.execSQL(DATABASE_CREATE);
insertRow(PRIVACY_LEVEL_ROW_INDEX,0,db);
insertRow(STREAM_TITLE_ROW_INDEX,untitled,db);
insertRow(STREAM_TAGS_ROW_INDEX,,db);
}

方法insertRow()的问题是它不能防止复制


div>

您可以使用列约束 UNIQUE


UNIQUE约束导致在指定列上创建唯一索引。



I would like to create a table to store device settings. The table has three rows: id, parameter_name and parameter_value.

The table was created by executing the following query statement:

DATABASE_CREATE = "create table DATABASE_TABLE (KEY_ID INTEGER PRIMARY KEY AUTOINCREMENT, KEY_NAME INTEGER not null, VALUE TEXT not null);

and then the rows are stored by executing the following method:

private long insertRow(int rowParameter, String rowValue, SQLiteDatabase db){
    long res = -1;
    ContentValues settingsParameterValues = new ContentValues();
    settingsParameterValues.put(KEY_NAME, rowParameter);
    settingsParameterValues.put(VALUE, rowValue);
    if(db != null){
        res = db.insert(DATABASE_TABLE, null, settingsParameterValues);
    }
    return res;
}

When the database is created the default values are stored:

@Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
        insertRow(PRIVACY_LEVEL_ROW_INDEX, "0", db);
        insertRow(STREAM_TITLE_ROW_INDEX, "untitled", db);
        insertRow(STREAM_TAGS_ROW_INDEX, "", db);
    }

The problem with method insertRow() however is that it can't prevent duplicating the entries.

Does anyone know how to prevent duplicate entries in this case?

解决方案

You can use the column constraint UNIQUE.

The UNIQUE constraint causes an unique index to be created on the specified columns.

这篇关于SQLite:防止重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆