SQLiteDatabase insert()方法始终返回-1

时间:2019-03-17 22:18:13

标签: android sqlite

我有一个数据库 Shelter.db ,其中包含一个名为“ 宠物”的表: 它的模式是

CREATE TABLE pets (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NUL, breed TEXT NOT NUL, gender INTEGER NOT NULL DEFAULT 0, weight INTEGER NOT NULL DEFAULT 0);

我正在尝试使用插入功能添加新行。此函数必须返回此添加的ID。但是,当我从调试器检查此代码时,我看到它返回-1。

这是“ SQLiteOpenHelper.cs”

PetDbHelper.cs

public class PetDbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "shelter.db";
    private static final int DATABASE_VERSION = 1;

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

    @Override
    public void onCreate(SQLiteDatabase db) {

        /*CREATE TABLE pets (_id INTEGER, name TEXT, breed TEXT, gender INTEGER, weight INTEGER);*/

        // Create a String that contains the SQL statement to create the pets table
        String SQL_CREATE_PETS_TABLE = "CREATE TABLE " + PetEntry.TABLE_NAME + "("
                + PetEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + PetEntry.COLUMN_PET_NAME + "TEXT NOT NULL, "
                + PetEntry.COLUMN_PET_BREED + "TEXT NOT NULL, "
                + PetEntry.COLUMN_PET_GENDER + "INTEGER NOT NULL DEFAULT 0, "
                + PetEntry.COLUMN_PET_WEIGHT + "INTEGER NOT NULL DEFAULT 0);" ;

        // Execute the SQL statement
        db.execSQL(SQL_CREATE_PETS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

这是我要插入新行的地方

private void insertPet() {
 PetDbHelper mDbHelper = new PetDbHelper(this);

// Gets the database in write mode
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

      ContentValues values = new ContentValues();
    values.put(PetEntry.COLUMN_PET_NAME, "Toto");
    values.put(PetEntry.COLUMN_PET_BREED, "Terrier");
    values.put(PetEntry.COLUMN_PET_GENDER, PetEntry.GENDER_MALE);
    values.put(PetEntry.COLUMN_PET_WEIGHT, 7);

    try {
        long newRowId = db.insert(PetEntry.TABLE_NAME, null, values);
    }catch (Exception e)
    {
        Log.e("Exception","SQLException"+String.valueOf(e.getMessage()));
        e.printStackTrace();

    }
}

每次返回-1 !!!!!!!!

1 个答案:

答案 0 :(得分:2)

I fixed your CREATE TABLE statement. You're missing spaces between the column names and the data types:

  private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " +
      PetEntry.TABLE_NAME + " (" +
      PetEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
      PetEntry.COLUMN_PET_NAME + " TEXT NOT NULL, " +
      PetEntry.COLUMN_PET_BREED + " TEXT, " +
      PetEntry.COLUMN_PET_GENDER + " INTEGER NOT NULL, " +
      PetEntry.COLUMN_PET_WEIGHT + " INTEGER NOT NULL DEFAULT 0);";