在使用eclipse在android中将数据插入SQLite之前检查重复值?

时间:2014-01-15 11:49:48

标签: android

您可以在下面的代码中帮助我吗?

一旦插入123 id 的记录,下次再次接受123 id再插入数据库....所以请帮我完成这个项目...

package com.example.finder;

import android.app.Activity;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.graphics.Color;

import android.graphics.Typeface;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.widget.TableLayout;

import android.widget.TableRow;

import android.widget.TextView;

import android.widget.Toast;

public class AdminActivity extends Activity {

String id,name,email;
SQLiteDatabase db;
TableRow tableRow;
TextView textview,textview1,textview2,textview3,textview4,textview5;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_admin);
    db=openOrCreateDatabase("EMP",MODE_PRIVATE,null);
    db.execSQL("CREATE TABLE IF NOT EXISTS EMP(id integer primary key,name varchar,email varchar);");
}

public void Submit(View view)
{       
    EditText edittext1=(EditText) findViewById(R.id.id);
    EditText edittext2=(EditText) findViewById(R.id.name);
    EditText edittext3=(EditText) findViewById(R.id.email);
    id=edittext1.getText().toString();
    name=edittext2.getText().toString();
    email=edittext3.getText().toString();
    db.execSQL("INSERT INTO EMP(id,name,email) values ('"+id+"','"+name+"','"+email+"');");

    if(id.equals("") && name.equals("") && email.equals(""))
    {
        Toast.makeText(getApplicationContext(), "Please enter details and submit", Toast.LENGTH_SHORT).show();
    }
    else 
        if(id.equals(""))
       {
            Toast toast=new Toast (getApplicationContext());
            toast.setDuration(Toast.LENGTH_LONG);
            Toast.makeText(getApplicationContext(), "Enter id....", Toast.LENGTH_SHORT).show();
       }
    else
        if(name.equals(""))
           {
            Toast toast=new Toast (getApplicationContext());
            toast.setDuration(Toast.LENGTH_LONG);
            Toast.makeText(getApplicationContext(), "Enter Name....", Toast.LENGTH_SHORT).show();
           }
        else
             if(email.equals(""))
            {
            Toast toast=new Toast (getApplicationContext());
            toast.setDuration(Toast.LENGTH_LONG);
             Toast.makeText(getApplicationContext(), "Enter email.....", Toast.LENGTH_SHORT).show();
            }
             else 
                { 
                    Toast toast=new Toast (getApplicationContext());
                    toast.setDuration(Toast.LENGTH_LONG);
                    edittext1.setText("");
                    edittext2.setText("");
                    edittext3.setText("");
                    Toast.makeText(getApplicationContext(), "Data submitted successfully", Toast.LENGTH_SHORT).show();
                    db.close();
                 }
            }

public void Showdata(View view)
{       
    Cursor c=db.rawQuery("SELECT * FROM EMP;",null);
    int count=c.getCount();
    c.moveToFirst();
    TableLayout tableLayout= new TableLayout(getApplicationContext());
    tableLayout.setVerticalScrollBarEnabled(true);
    TableRow tableRow;
    TextView textview,textview1,textview2,textview3,textview4,textview5;
    tableRow=new TableRow(getApplicationContext());
    textview=new TextView(getApplicationContext());
    textview.setText("Empid");
    textview.setTextColor(Color.RED);
    textview.setTypeface(null,Typeface.BOLD);
    textview.setPadding(0, 5, 3, 5);
    tableRow.addView(textview);
    textview4=new TextView(getApplicationContext());
    textview4.setText("Ename");
    textview4.setTextColor(Color.RED);
    textview4.setTypeface(null,Typeface.BOLD);
    textview4.setPadding(15, 10, 3, 5);
    tableRow.addView(textview4);
    textview5=new TextView(getApplicationContext());
    textview5.setText("Email");
    textview5.setTextColor(Color.RED);
    textview5.setTypeface(null,Typeface.BOLD);
    textview5.setPadding(25, 5, 3, 5);
    tableRow.addView(textview5);
    tableLayout.addView(tableRow);
    for (Integer j=0; j< count; j++)
    {
    tableRow= new TableRow(getApplicationContext());
    textview1=new TextView(getApplicationContext());
    textview1.setText(c.getString(c.getColumnIndex("id")));
    textview2=new TextView(getApplicationContext());
    textview2.setText(c.getString(c.getColumnIndex("name")));
    textview3=new TextView(getApplicationContext());
    textview3.setText(c.getString(c.getColumnIndex("email")));
    textview1.setPadding(0, 5, 3, 5);
    textview2.setPadding(15, 5, 3, 5);
    textview3.setPadding(25, 5, 3, 5);
    tableRow.addView(textview1);
    tableRow.addView(textview2);
    tableRow.addView(textview3);
    tableLayout.addView(tableRow);
    c.moveToNext();
    }
    setContentView(tableLayout);
    db.close();
}

public void Exit(View view){
    System.exit(0);
}

}

3 个答案:

答案 0 :(得分:1)

我通过使用所谓的 upserts (UPSERT = UPDATE OR INSERT)替换所有插入内容和更新来解决此问题。

String[] args = {"1", "newOrOldCategory"}; // where 1 is the category id
getWritableDatabase().execSQL("INSERT OR REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)", args);

或者(我目前的实施):

String[] args = {"1", "newOrOldCategory"}; // where 1 is the category id
getWritableDatabase().execSQL("REPLACE INTO table_name (idColoumn, categoryColumn) VALUES (?, ?)", args);

更改表和字段名称以匹配您的值,以及值。

简单有效:如果记录不存在,则插入记录,否则使用传递的值更新记录。

无需使用最差做法

1 - update, check for error and (if so) insert  

或(最糟糕的!)

2 - delete + insert

答案 1 :(得分:0)

如上所述,您可以通过检查db是否存在表中的id以及一些有效条目来执行此操作。如果不存在,则只插入新数据。

或者,如果您不想完全重复,也可以在自动增量模式下设置ID,因此不存在重复。

答案 2 :(得分:0)

use unique Key for that column and catch exception while inserting record.

like here name is unique so we cant insert duplicate name.


private static final String DATABASE_CREATE_TABLE_CLIENT = "create table " + DATABASE_TABLE_NAME_CLIENTS + "(_id integer primary key autoincrement,"+ NAME +" 
text not null ,"+ MOBILENO +" text not null," +COMPANYNAME+"  text not null,unique ("+NAME+"))";



try
        {
//          

            sqlite.execSQL("INSERT INTO "+DATABASE_TABLE_NAME_CLIENT +"("+CLIENTID+","+NAME+","+MOBILENO+","+COMPANYNAME+") 
values " +
                    "('"+clientid+"','"+name+"','"+mobileno+"','"+comname+"')");
        }

        catch(SQLiteConstraintException e)
        {
            Toast.makeText(context, "Please Enter different name....", Toast.LENGTH_LONG).show();
        }

may this answer help you