检查行是否已存在于 sqlite 数据库中

check if row already exist in sqlite database

LogCat error:

FATAL EXCEPTION: main
                                                                      Process: com.sam.shoppingcart, PID: 31773
                                                                      android.database.sqlite.SQLiteException: near "Beef": syntax error (code 1): , while compiling: SELECT KEY_NAME FROM shop WHERE KEY_NAME=Corned Beef
                                                                          at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                          at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:893)
                                                                          at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:504)
                                                                          at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                          at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                          at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                                          at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                          at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1339)
                                                                          at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1278)
                                                                          at com.sam.shoppingcart.SQLiteHandler.ifExists(SQLiteHandler.java:63)
                                                                          at com.sam.shoppingcart.CustomListAdapter.onClick(CustomListAdapter.java:77)

我有一个使用带有 "Add" 和 "Remove" 按钮的自定义适配器的列表视图。当单击添加按钮时,LV 项目的名称和价格被添加到数据库中。我想在添加时检查 LV 项目是否已经存在于数据库中。为此,我在 DBHandler 中创建了 ifExists(Model model) 函数。但是现在单击“添加”按钮时出现错误。我做错了什么? PS: 我从 here.

得到了函数

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayList<Model> mListData;
    private CustomListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView)findViewById(R.id.list);


        mListData = new ArrayList<>();

        mListData.add(new Model("Beef Manhattan", "50"));
        mListData.add(new Model("Chicken Fried Steak", "90"));
        mListData.add(new Model("Corned Beef", "100"));
        mListData.add(new Model("Domesticated Turkey", "80"));
        mListData.add(new Model("Eggs Benedict", "10"));
        mListData.add(new Model("French Dip", "20"));
        mListData.add(new Model("Green Bean Casserole", "30"));
        mListData.add(new Model("Potato Salad", "40"));
        mListData.add(new Model("Pumpkin Pie", "60"));
        mListData.add(new Model("Salisbury Steak", "70"));

        adapter = new CustomListAdapter(this, R.layout.listrow, mListData);
        listView.setAdapter(adapter);



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action) {

            startActivity(new Intent(MainActivity.this, NextActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}
public class CustomListAdapter extends ArrayAdapter<Model> {

    private Context mContext;
    int resource;
    private ArrayList<Model> mListData = new ArrayList<Model>();



    public CustomListAdapter(Context mContext, int resource, ArrayList<Model> mListData) {
        super(mContext, resource, mListData);
        this.resource = resource;
        this.mContext = mContext;
        this.mListData = mListData;
    }

    public void setListData(ArrayList<Model> mListData) {
        this.mListData = mListData;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        View v = convertView;
        final ViewHolder holder;
        if (v == null) {
            holder = new ViewHolder();

            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();

                v = inflater.inflate(resource, parent, false);

                holder.name = (TextView) v.findViewById(R.id.name);
                holder.rate = (TextView) v.findViewById(R.id.rate);
                holder.add = (Button) v.findViewById(R.id.add);
                holder.remove = (Button) v.findViewById(R.id.remove);


            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }




        final Model item = mListData.get(position);

            holder.name.setText(item.getName());
            holder.rate.setText(item.getRate());
            holder.add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   SQLiteHandler db = new SQLiteHandler(getContext());

                    if(db.ifExists(item)){


                        Toast.makeText(getContext(), "Already Present", Toast.LENGTH_SHORT).show();

                    }else{
                        db.addItems(holder.name.getText().toString(), holder.rate.getText().toString());
                        Toast.makeText(getContext(), "Added", Toast.LENGTH_SHORT).show();
                    }


                }
            });

            holder.remove.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SQLiteHandler db = new SQLiteHandler(getContext());
                    db.deleteItem(item);
                    Toast.makeText(getContext(), "Removed", Toast.LENGTH_SHORT).show();

                }
            });

        return v;
    }

    class ViewHolder {

        TextView name;
        TextView rate;
        Button add;
        Button remove;
    }

}
public class SQLiteHandler extends SQLiteOpenHelper {

 private static final String TAG = SQLiteHandler.class.getSimpleName();

 // All Static variables
 // Database Version
 private static final int DATABASE_VERSION = 1;

 // Database Name
 private static final String DATABASE_NAME = "android_api";

 // Profile Settings table name
 private static final String TABLE_SHOP = "shop";

 // Profile Settings information names
 private static final String KEY_ID = "id";
 private static final String KEY_NAME = "name";
 private static final String KEY_PRICE = "price";


 public SQLiteHandler(Context context) {
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }

 // Creating Tables
 @Override
 public void onCreate(SQLiteDatabase db) {

  String CREATE_PROF_TABLE = "CREATE TABLE " + TABLE_SHOP + "("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_NAME+" TEXT,  "+KEY_PRICE+" TEXT" + ")";

  db.execSQL(CREATE_PROF_TABLE);

  Log.d(TAG, "Database tables created");
 }

 // Upgrading database
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // Drop older table if existed
  db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHOP);

  // Create tables again
  onCreate(db);
 }

 // Check before adding item if item already exist
 SQLiteDatabase db = this.getWritableDatabase();
 public boolean ifExists(Model model) {
  Cursor cursor = null;
  String checkQuery = "SELECT KEY_NAME FROM "+TABLE_SHOP+" WHERE KEY_NAME="+model.getName();
  cursor= db.rawQuery(checkQuery,null);
  boolean exists = (cursor.getCount() > 0);
  cursor.close();
  return exists;
 }


    // Add items to db
 public void addItems(String name, String mobile){

  SQLiteDatabase db = this.getWritableDatabase();

  ContentValues values = new ContentValues();

  values.put(KEY_NAME, name);
  values.put(KEY_PRICE, mobile);

  long id = db.insert(TABLE_SHOP, null, values); // insert to 1st row
  db.close(); // Closing database connection

  Log.d(TAG, "New products inserted into sqlite: " + id);

 }




 // Fetch all data
 public ArrayList<HashMap<String, String>> getProfDetails()
    {
        ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>();

        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT  * FROM " + TABLE_SHOP;
        Cursor res = db.rawQuery(selectQuery, null);
        res.moveToFirst();

        while (res.isAfterLast() == false)
        {
            HashMap<String, String> hashmap= new HashMap<String, String>();
            hashmap.put("name", res.getString(res.getColumnIndex(KEY_NAME)));
            hashmap.put("price", res.getString(res.getColumnIndex(KEY_PRICE)));

            array_list.add(hashmap);
            res.moveToNext();
        }
        return array_list;
    }

 // Getting Sum of "price"
 public int sumofPrice(){
  SQLiteDatabase db = this.getReadableDatabase();
  String selectQuery = "SELECT  SUM(price) FROM " + TABLE_SHOP;
  Cursor cur = db.rawQuery(selectQuery, null);
  int total=0;
  if(cur.moveToFirst())
  {
   total = cur.getInt(0);
  }
  return total;
 }

 // Delete single row
 public void deleteItem(Model model) {
  SQLiteDatabase db = this.getWritableDatabase();
  db.delete(TABLE_SHOP, KEY_NAME + " = ?",new String[] { String.valueOf(model.getName()) });
  db.close();
 }

 // Delete whole table
 public void deleteTable() {
  SQLiteDatabase db = this.getWritableDatabase();
  // Delete All Rows
  db.delete(TABLE_SHOP, null, null);
  db.close();

  Log.d(TAG, "Deleted all info from sqlite");
 }

}

在你的 ifExists 函数中

String checkQuery = "SELECT KEY_NAME FROM "+TABLE_SHOP+" WHERE KEY_NAME="+model.getName();

改为

 String checkQuery = "SELECT "+KEY_NAME+" FROM "+TABLE_SHOP+" WHERE "+KEY_NAME+"="+model.getName();

在下面检查您更新的 ifExists() 方法,

     public boolean ifExists(Model model)
     {
         Cursor cursor = null;
         String checkQuery = "SELECT " + KEY_NAME + " FROM " + TABLE_SHOP + " WHERE " + KEY_NAME + "= '"+model.getName() + "'";
          cursor= db.rawQuery(checkQuery,null);
          boolean exists = (cursor.getCount() > 0);
          cursor.close();
          return exists;
     }

有两件事,首先是您将变量作为列名的值传递,其次是您使用 space 传递名称值并且没有引用它们所以它会导致应用程序崩溃。

现在试试上面的代码。

private boolean hasRow(String id) {
        String selectString = "SELECT * FROM " + tablename + " WHERE " +
                id + " =?";
        sqliteDatabase = getReadableDatabase();
        Cursor cursor = sqliteDatabase.rawQuery(selectString, new String[] {id});

        boolean hasObject = false;
        if(cursor.moveToFirst()){
            hasObject = true;
        }

        cursor.close();
        sqliteDatabase.close(); //Close the database
        return hasObject; //return value.
    }

这将找到第一个出现的地方,并说是的,这一行存在。 要获得有多少行,请使用

while(cursor.moveToNext()) {
count++;
}