1

我查看了有关此主题的其他问题,但没有一个答案适用和/或对我有用。我在尝试插入数据库时​​收到“SQLiteConstraintException:错误代码 19:约束失败”错误。

这是我的数据库:

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;


public class StrongDbAdapter {

    public static final String KEY_TITLE = "title";
    public static final String KEY_BODY = "body";
    public static final String KEY_ROWID = "_id";



    public static final String WORKOUT_STATE = "workoutState";

    public static final String SQUAT_LABEL = "squatLabel";




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


    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "notes";
    private static final int DATABASE_VERSION = 2;



    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
        "create table notes (_id integer primary key autoincrement , "
        + "title text, workoutState text ," +
        " squatLabel text );";



    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

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

        @Override
        public void onCreate(SQLiteDatabase db) {

            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 notes");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public StrongDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the notes database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public StrongDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }


    /**
     * Create a new note using the title and body provided. If the note is
     * successfully created return the new rowId for that note, otherwise return
     * a -1 to indicate failure.

     */
    public long createNote(String title, String squatLabel) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_TITLE, title);
        //initialValues.put(WORKOUT_STATE, workoutState);
        initialValues.put(SQUAT_LABEL, squatLabel);

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

    /**
     * Delete the note with the given rowId
     * 
     * @param rowId id of note to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteNote(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list of all notes in the database
     * 
     * @return Cursor over all notes
     */
    public Cursor fetchAllNotes() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE,
                WORKOUT_STATE}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the note that matches the given rowId
     * 
     * @param rowId id of note to retrieve
     * @return Cursor positioned to matching note, if found
     * @throws SQLException if note could not be found/retrieved
     */
    public Cursor fetchNote(long rowId) throws SQLException {

        Cursor mCursor =

            mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_TITLE, WORKOUT_STATE}, KEY_ROWID + "='" + rowId+"'", null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Update the note using the details provided. The note to be updated is
     * specified using the rowId

     * @param rowId id of note to update
     * @param title value to set note title to
     * @return true if the note was successfully updated, false otherwise
     */
    public boolean updateNote(long rowId, String title) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        //args.put(WORKOUT_STATE, workoutState);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

这是我的 WorkoutEdit 类中的插入方法

//Saves all the data to the database
    private void saveState() {
        String title = workoutState;
        String squatLabel = squats.getText().toString();


        if (mRowId == null) {
            long id = mDbHelper.createNote(title, squatLabel);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateNote(mRowId, title);
        }
    }

最后,我的 LogCat!

08-04 23:09:22.009: E/Database(26575): Error inserting squatLabel=Squats - 45 title=WorkoutB
08-04 23:09:22.009: E/Database(26575): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
08-04 23:09:22.009: E/Database(26575):  at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
08-04 23:09:22.009: E/Database(26575):  at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java)
08-04 23:09:22.009: E/Database(26575):  at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1677)
08-04 23:09:22.009: E/Database(26575):  at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1521)
08-04 23:09:22.009: E/Database(26575):  at com.anapoleon.android.stronglifts.StrongDbAdapter.createNote(StrongDbAdapter.java:163)
08-04 23:09:22.009: E/Database(26575):  at com.anapoleon.android.stronglifts.WorkoutEdit.saveState(WorkoutEdit.java:232)
08-04 23:09:22.009: E/Database(26575):  at com.anapoleon.android.stronglifts.WorkoutEdit.onPause(WorkoutEdit.java:214)
08-04 23:09:22.009: E/Database(26575):  at android.app.Activity.performPause(Activity.java:4046)
08-04 23:09:22.009: E/Database(26575):  at android.app.Instrumentation.callActivityOnPause(Instrumentation.java)
08-04 23:09:22.009: E/Database(26575):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2819)
08-04 23:09:22.009: E/Database(26575):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2789)
08-04 23:09:22.009: E/Database(26575):  at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:2762)
08-04 23:09:22.009: E/Database(26575):  at android.app.ActivityThread.access$1700(ActivityThread.java:135)
08-04 23:09:22.009: E/Database(26575):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
08-04 23:09:22.009: E/Database(26575):  at android.os.Handler.dispatchMessage(Handler.java)
08-04 23:09:22.009: E/Database(26575):  at android.os.Looper.loop(Looper.java)
08-04 23:09:22.009: E/Database(26575):  at android.app.ActivityThread.main(ActivityThread.java:4385)
08-04 23:09:22.009: E/Database(26575):  at java.lang.reflect.Method.invokeNative(Native Method)
08-04 23:09:22.009: E/Database(26575):  at java.lang.reflect.Method.invoke(Method.java:507)
08-04 23:09:22.009: E/Database(26575):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
08-04 23:09:22.009: E/Database(26575):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
08-04 23:09:22.009: E/Database(26575):  at dalvik.system.NativeStart.main(Native Method)

先感谢您!

4

1 回答 1

2

您必须弄清楚您的插入违反了 SQLite 数据库中的哪个数据库约束。我所知道的最好的方法是根据您尝试插入的数据直观地验证每个约束。

要获取每个表的约束列表,可以执行以下 SQL:

select sql from sqlite_master 
where type='table' and name='your_table_name';
于 2012-08-05T03:51:23.973 回答