android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed

來源:互聯網
上載者:User

在android進行單元測試時,測試了自己編寫的添加資料到資料庫的函數,其測試函數如下:

public void testAdd() {

StudentDAO studentDAO = new StudentDAO(this.getContext());

Student student = new Student(1, "lily", 20);

studentDAO.add(student);

Log.i(TAG, "testAdd");

}

第一次測試成功,但再測試一次就失敗了,其錯誤提示如下:

android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed

at android.database.sqlite.SQLiteStatement.native_execute(Native Method)

at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:55)

at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1772)

at com.android.sqlite.dao.StudentDAO.add(StudentDAO.java:26)

at com.android.sqlite.activity.StudentDAOTest.testAdd(StudentDAOTest.java:16)

at java.lang.reflect.Method.invokeNative(Native Method)

at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)

at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)

at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)

at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)

 

找了半天也沒發現自己的插入語句有哪裡錯誤,最後才知道我在student表中把學生id設成了主鍵,第一次插入正確,當第二次測試時相當於再次插入同樣的資訊,由於id已存在,所以拋出了異常。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.