无法将数据添加到 android 中的 SQLite table

Unable to add data to SQLite table in android

我正在开发一个简单的 SQLite CRUD 应用程序,我想将数据添加到在 SQLite 中手动创建的数据库中。但是当我添加数据时,应用程序停止并显示以下错误消息

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sqlitecrudexample, PID: 14124
    android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: employees.id (code 1299 SQLITE_CONSTRAINT_NOTNULL)
        at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
        at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:890)
        at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:756)
        at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:66)
        at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1920)
        at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1897)
        at com.example.sqlitecrudexample.MainActivity.addEmployee(MainActivity.kt:70)
        at com.example.sqlitecrudexample.MainActivity.access$addEmployee(MainActivity.kt:13)
        at com.example.sqlitecrudexample.MainActivity$onCreate.onClick(MainActivity.kt:30)
        at android.view.View.performClick(View.java:7448)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access00(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 14124 SIG: 9

这是我创建数据并将数据添加到 table

的代码
private fun addEmployee(){
        var name:String = editTextName.text.toString().trim()
        var salary:String = editTextSalary.text.toString().trim()
        var dept = spinnerDepartment.selectedItem.toString()

        var calendar = Calendar.getInstance()
        var simpleDateFormat = SimpleDateFormat("yyyy-mm-dd hh:mm:ss")
        var joiningDate = simpleDateFormat.format(calendar.time)

        if(inputsAreCorrect(name,salary)){
            val insertSQL = """
                INSERT INTO employees 
                (name, department, joiningdate, salary)
                VALUES 
                (?, ?, ?, ?);
                """.trimIndent()
            mDatabase.execSQL(insertSQL, arrayOf(name, dept, joiningDate, salary))
            Toast.makeText(this,"Employee Added Successfully",Toast.LENGTH_SHORT).show()
        }
    }

    private fun createEmployeeTable() {
        mDatabase.execSQL(
            """CREATE TABLE IF NOT EXISTS employees (
                    id int PRIMARY KEY AUTOINCREMENT NOT NULL,
                    name varchar(200) NOT NULL,
                    department varchar(200) NOT NULL,
                    joiningdate datetime NOT NULL,
                    salary double NOT NULL
                );"""
        )
    }

这是我的数据class

data class Employee(
    var id: Int,
    var name: String,
    var dept: String,
    var joiningDate: String,
    var salary: Double
)

您在定义 id 行时使用了不正确的语法,您必须仅使用 Integer 作为关键字 AUTOINCREMENT can be used with INTEGER 字段。如下更改您的 create table 语法,它将起作用

id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,

将 ID 行的 SQL 语句更改为“INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL”。你需要使用原始类型

如果您真的尝试使用此语句创建 table:

CREATE TABLE IF NOT EXISTS employees (
  id int PRIMARY KEY AUTOINCREMENT NOT NULL,
  ..........................
);

结果会是这个错误:

AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY

因此,我的猜测是 table 不是由该语句创建的,而是由您稍后对其进行更改的先前语句创建的。这些更改实际上并未反映到数据库中,因为 table 已经存在。

您需要做的是从设备上卸载应用程序以删除数据库,或者更改 SQLiteOpenHelper 中的数据库版本 class 以便调用 onUpgrade() 方法删除并重新创建 table.

所以把CREATE语句改成:

CREATE TABLE IF NOT EXISTS employees (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  ..........................
);

此外,不要使用 execSQL() 在 table 中插入行。
推荐的方法是insert():

val cv = ContentValues()
cv.put("name", name)
cv.put("department", dept)
cv.put("joiningdate", joiningDate)
cv.put("salary", salary)
mDatabase.insert("employees", null, cv)