如果值已存在,则Android Studio Sqlite不会在数据库中插入

时间:2016-07-08 07:44:11

标签: android sqlite

也许这个问题是重复的,但我找不到与我的代码类似的答案。

我想在插入之前检查数据库值。

如果存在值,我想跳过并继续下一次插入。

这是我的插入

public void insertPlayer1Songlist() {

        createPlayer1("Song Title 1", "Artist 1", "Vol 1","","0","12341");
        createPlayer1("Song Title 2", "Artist 2", "Vol 2","","0","12342");
        createPlayer1("Song Title 3", "Artist 3", "Vol 3","","0","12343");
        createPlayer1("Song Title 4", "Artist 4", "Vol 4","","0","12344");
        createPlayer1("Song Title 5", "Artist 5", "Vol 5","","0","12345");
        createPlayer1("Song Title 6", "Artist 6", "Vol 6","","0","12346");
        createPlayer1("Song Title 7", "Artist 7", "Vol 7","","0","12347");
        createPlayer1("Song Title 8", "Artist 8", "Vol 8","","0","12348");
        createPlayer1("Song Title 9", "Artist 9", "Vol 9","","0","12349");
        createPlayer1("Song Title 10", "Artist 10", "Vol 10","","0","12310");
        createPlayer1("Song Title 11", "Artist 11", "Vol 11","","0","12311");
        createPlayer1("Song Title 12", "Artist 12", "Vol 12","","0","12312");

    }

这里是我想检查数据库中是否已有值的地方..

public long createPlayer1(String title,
                              String artist, String volume,
                              String type, String favorite, String number) {

        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_ARTIST, artist);
        initialValues.put(KEY_VOLUME, volume);
        initialValues.put(KEY_TYPE, type);
        initialValues.put(KEY_FAVORITE, favorite);
        initialValues.put(KEY_NUMBER, number);

        return mDb.insert(SQLITE_TABLE, null, initialValues);
    }

我想检查数字是否已存入数据库。

如果是,我想跳过并继续使用此代码。

return mDb.insert(SQLITE_TABLE, null, initialValues);

完整代码..

package com.magicstarme.virtualsongbook;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;


/**
 * Created by Joe on 7/7/2016.
 */
public class FragmentOne_DbAdapter {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_TITLE = "title";
    public static final String KEY_ARTIST = "artist";
    public static final String KEY_VOLUME = "volume";
    public static final String KEY_TYPE = "type";
    public static final String KEY_FAVORITE = "favorite";
    public static final String KEY_NUMBER = "number";

    private static final String TAG = "FragmentOne_DbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "Virtualsongbook";
    private static final String SQLITE_TABLE = "Player1";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private static final String DATABASE_CREATE =
            "CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
                    KEY_ROWID + " integer PRIMARY KEY autoincrement," +
                    KEY_TITLE + "," +
                    KEY_ARTIST + "," +
                    KEY_VOLUME + "," +
                    KEY_TYPE + "," +
                    KEY_FAVORITE + "," +
                    KEY_NUMBER + ")";

    private static class DatabaseHelper extends SQLiteOpenHelper {

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


        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.w(TAG, DATABASE_CREATE);
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
            onCreate(db);
        }
    }

    public FragmentOne_DbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public FragmentOne_DbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        if (mDbHelper != null) {
            mDbHelper.close();
        }
    }

    private boolean isRecordExistInDatabase(String tableName, String field, String value) {
        Cursor c = mDb.rawQuery("SELECT * FROM " + tableName + " WHERE " + field + "=" + value, null);
        if (c.moveToFirst()) {
            //Record exist
            c.close();
            return true;
        }
        //Record available
        c.close();
        return false;
    }


    public long createPlayer1(String title,
                              String artist, String volume,
                              String type, String favorite, String number) {

        if(isRecordExistInDatabase(SQLITE_TABLE, KEY_NUMBER, number)){
            return 0;
        }

        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_ARTIST, artist);
        initialValues.put(KEY_VOLUME, volume);
        initialValues.put(KEY_TYPE, type);
        initialValues.put(KEY_FAVORITE, favorite);
        initialValues.put(KEY_NUMBER, number);

        return mDb.insert(SQLITE_TABLE, null, initialValues);
    }

    public boolean deleteAllPlayer1() {

        int doneDelete = 0;
        doneDelete = mDb.delete(SQLITE_TABLE, null , null);
        Log.w(TAG, Integer.toString(doneDelete));
        return doneDelete > 0;

    }

    public Cursor fetchPlayer1ByTitle(String titleText) throws SQLException {
        Log.w(TAG, titleText);
        Cursor mCursor = null;
        if (titleText == null  ||  titleText.length () == 0)  {
            mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                            KEY_TITLE, KEY_ARTIST, KEY_VOLUME, KEY_TYPE, KEY_FAVORITE, KEY_NUMBER},
                    null, null, null, null, null);

        }
        else {
            mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
                            KEY_TITLE, KEY_ARTIST, KEY_VOLUME, KEY_TYPE, KEY_FAVORITE, KEY_NUMBER},
                    KEY_TITLE + " like '%" + titleText + "%'", null,
                    null, null, null, null);
        }
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    public Cursor fetchAllPlayer1() {

        Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
                        KEY_TITLE, KEY_ARTIST, KEY_VOLUME, KEY_TYPE, KEY_FAVORITE, KEY_NUMBER},
                null, null, null, null, null);

        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public boolean updateItemFavorite(long rowId, String favorite) {
        int doneUpdate = 0;
        ContentValues values = new ContentValues();
        values.put(KEY_FAVORITE, favorite);
        //doneUpdate =  mDb.update(SQLITE_TABLE, values, KEY_ROWID + " = ?", new String[] { String.valueOf(rowId) });
        doneUpdate =  mDb.update(SQLITE_TABLE, values, KEY_ROWID + "=" + rowId,null);
        Log.w(TAG, Integer.toString(doneUpdate));
        return doneUpdate > 0;
        //return mDb.update(SQLITE_TABLE, values, KEY_ROWID+"="+rowId,null);
    }

    public void insertPlayer1Songlist() {

        //TYPE
        //0 - NONE
        //1 - NEW

        createPlayer1("Song Title 1", "Artist 1", "Vol 1","0","0","12341");
        createPlayer1("Song Title 2", "Artist 2", "Vol 2","0","0","12342");
        createPlayer1("Song Title 3", "Artist 3", "Vol 3","0","0","12343");
        createPlayer1("Song Title 4", "Artist 4", "Vol 4","0","0","12344");
        createPlayer1("Song Title 5", "Artist 5", "Vol 5","0","0","12345");
        createPlayer1("Song Title 6", "Artist 6", "Vol 6","0","0","12346");
        createPlayer1("Song Title 7", "Artist 7", "Vol 7","0","0","12347");
        createPlayer1("Song Title 8", "Artist 8", "Vol 8","0","0","12348");
        createPlayer1("Song Title 9", "Artist 9", "Vol 9","0","0","12349");
        createPlayer1("Song Title 10", "Artist 10", "Vol 10","0","0","12310");
        createPlayer1("Song Title 11", "Artist 11", "Vol 11","0","0","12311");
        createPlayer1("Song Title 12", "Artist 12", "Vol 12","0","0","12312");

        /*createPlayer1("Song Title 1", "Artist 1", "Vol 1","0","0","12341");
        createPlayer1("Song Title 1", "Artist 1", "Vol 1","0","0","12341");
        createPlayer1("Song Title 1", "Artist 1", "Vol 1","0","0","12341");
        createPlayer1("Song Title 1", "Artist 1", "Vol 1","0","0","12341");
        createPlayer1("Song Title 2", "Artist 2", "Vol 2","0","0","12342");
        createPlayer1("Song Title 2", "Artist 2", "Vol 2","0","0","12342");
        createPlayer1("Song Title 2", "Artist 2", "Vol 2","0","0","12342");
        createPlayer1("Song Title 2", "Artist 2", "Vol 2","0","0","12342");
        createPlayer1("Song Title 2", "Artist 2", "Vol 2","0","0","12342");
        createPlayer1("Song Title 12", "Artist 12", "Vol 12","0","0","12312");
        createPlayer1("Song Title 12", "Artist 12", "Vol 12","0","0","12312");
        createPlayer1("Song Title 12", "Artist 12", "Vol 12","0","0","12312");
        createPlayer1("Song Title 12", "Artist 12", "Vol 12","0","0","10000");*/

    }
}

请帮助我,

感谢。

3 个答案:

答案 0 :(得分:1)

Y

答案 1 :(得分:0)

         public boolean rowIdExists(String StrId) {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("select id from " + TABLE_USER
            + " where id=?", new String[]{StrId});
    boolean exists = (cursor.getCount() > 0);

    return exists;
   }


    public void insertuserrate(String Str[], Context cxt) {

    // TODO Auto-generated method stub

    String strId = "";

    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        {
            values.put(KEY_RID, Str[0]);
            values.put(ALL_name, Str[1]);

            if (rowIdExists(Str[0])) {
                db.update(TABLE_USER, values, "id " + "=" + Str[0], null);
            } else {
                db.insert(TABLE_USER, null, values);
            }
            //database connection
        }
        try {
            db.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
       } catch (Exception e) {
        e.printStackTrace();
      }

    }

答案 2 :(得分:0)

您可以检查数据库中是否存在数字,如下所示:

public long createPlayer1(String title,
                              String artist, String volume,
                              String type, String favorite, String number) {

        String query = "SELECT * FROM " + SQLITE_TABLE;
        Cursor cursor = mDb.rawQuery(query, null);
        int ColumeNumber = cursor.getColumnIndex("Number"); // your column title in the table

        while (cursor.moveToNext()) {
            String num = cursor.getString(ColumeNumber);
            if(num.equals(number)) return -1; // has existed, so not insert and return now
        }
        cursor.close();

        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_ARTIST, artist);
        initialValues.put(KEY_VOLUME, volume);
        initialValues.put(KEY_TYPE, type);
        initialValues.put(KEY_FAVORITE, favorite);
        initialValues.put(KEY_NUMBER, number);

        return mDb.insert(SQLITE_TABLE, null, initialValues);
    }