sqlite 如何在CREATE TABLE上插入数据?[已关闭]

epfja78i  于 2022-11-14  发布在  SQLite
关注(0)|答案(1)|浏览(148)

已关闭。此问题需要details or clarity。它目前不接受答案。
**想要改进这个问题吗?**添加细节,并通过editing this post澄清问题。

昨天关门了。
Improve this question
在使用Kotlin和SQLite的应用程序中,我希望创建一个pointTable表并立即插入第一个数据,但出现了运行时错误。我想要捕获错误代码,但它不起作用。怎么了?

lass SqliteHelper(context: Context?, name:String, version:Int):SQLiteOpenHelper(context, name, null, version) {

    // create table
    override fun onCreate(p0: SQLiteDatabase?) {
        try {
            p0?.execSQL("CREATE TABLE IF NOT EXISTS pointTable(id INTEGER PRIMARY KEY, pointValue INT)")
            p0?.let {
                initPoint(it)
            }
        } catch (err: Exception) {
            Log.d("test", err.toString())
            Log.d("test", err.stackTraceToString())
        }
    }

    fun initPoint(wd: SQLiteDatabase) {
        wd.execSQL("insert into pointTable(pointValue) values (0)")
        wd.close()
    }

}
override fun onCreate(p0: SQLiteDatabase) {
        val sqlArray = arrayOf(
            "CREATE TABLE IF NOT EXISTS questionTable" +
                    "(id INTEGER PRIMARY KEY," +
                    " num INT," +
                    " que TEXT," +
                    " abcArr Text," +
                    " opt1 Text, opt2 Text, opt3 Text, opt4 Text," +
                    " ans INT," +
                    " exp TEXT," +
                    " examName TEXT," +
                    " wrong INT, correct INT," +
                    " part1 TEXT, part2 TEXT, part3 TEXT, part4 TEXT, part5 TEXT, part6 TEXT, part7 TEXT )",
            "CREATE TABLE IF NOT EXISTS examTable(examName TEXT, downloadDate TEXT, myApply INT)",
            "CREATE TABLE IF NOT EXISTS pointTable(id INTEGER PRIMARY KEY, pointValue INT)"

        )
        sqlArray.forEach {
            p0.execSQL(it)
        }
        initPoint(p0)
    }

    private fun initPoint(wd:SQLiteDatabase){
        wd.execSQL("insert into pointTable(pointValue) values (5)")
    }
cbeh67ev

cbeh67ev1#

OnCreate方法中的代码没有任何错误,它工作得很好。InitPoint函数中的,wd.Close很可能会导致后续问题。
也就是说,当您第一次尝试访问数据库时,它调用onCreate,创建数据库,表被添加,但随后数据库被关闭(由wd.close()关闭),然后关闭的数据库可用于实际执行对数据库的访问。结果为异常,因为数据库已关闭。当您重新运行应用程序时,因为数据库现在存在,所以不会调用onCreate,并且该问题似乎已经得到修复,因为现在返回了一个打开的数据库。但是,如果该应用程序是分发的,则在第一次使用该应用程序时会发生例外。
也许可以考虑以下基于可用代码的工作示例(有关更改,请参阅注解)。这增加了一些额外的日志记录:-

class MainActivity : AppCompatActivity() {
    lateinit var dbHelper: SqliteHelper
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        dbHelper = SqliteHelper(this,"my_database.db",1)
        var db = dbHelper.writableDatabase // do something as otherwise database will not be created
        // inspect the resultant database schema again
        DatabaseUtils.dumpCursor(db.query("sqlite_master", null,null,null,null,null,null))
    }
}

class SqliteHelper(context: Context?, name:String, version:Int):
    SQLiteOpenHelper(context, name, null, version) {

    // create table
    override fun onCreate(p0: SQLiteDatabase?) {
        Log.d("test","onCreate invoked") // ADDED
        try {
            p0?.execSQL("CREATE TABLE IF NOT EXISTS pointTable(id INTEGER PRIMARY KEY, pointValue INT)")
            p0?.let {
                initPoint(it)
            }
        } catch (err: Exception) {
            Log.d("test", err.toString())
            Log.d("test", err.stackTraceToString())
        }
        //ADDED to inspect the resultant database schema
        DatabaseUtils.dumpCursor(p0?.query("sqlite_master", null,null,null,null,null,null))
    }

    // ADDED as required
    override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
    }
    
    fun initPoint(wd: SQLiteDatabase) {
        wd.execSQL("insert into pointTable(pointValue) values (0)")
        //wd.close() //<<<<<<<<<< DELETED as can cause problems be inefficient
    }
}

结果输出到日志(注意第一次运行,这是创建数据库的时间,后续运行只会在数据库存在时根据MainActivity进行记录):-

2022-11-13 19:02:17.190 D/test: onCreate invoked

2022-11-13 19:02:17.192 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@cf2ef01
2022-11-13 19:02:17.192 I/System.out: 0 {
2022-11-13 19:02:17.192 I/System.out:    type=table
2022-11-13 19:02:17.192 I/System.out:    name=android_metadata
2022-11-13 19:02:17.192 I/System.out:    tbl_name=android_metadata
2022-11-13 19:02:17.193 I/System.out:    rootpage=3
2022-11-13 19:02:17.193 I/System.out:    sql=CREATE TABLE android_metadata (locale TEXT)
2022-11-13 19:02:17.193 I/System.out: }
2022-11-13 19:02:17.193 I/System.out: 1 {
2022-11-13 19:02:17.193 I/System.out:    type=table
2022-11-13 19:02:17.193 I/System.out:    name=pointTable
2022-11-13 19:02:17.194 I/System.out:    tbl_name=pointTable
2022-11-13 19:02:17.194 I/System.out:    rootpage=4
2022-11-13 19:02:17.194 I/System.out:    sql=CREATE TABLE pointTable(id INTEGER PRIMARY KEY, pointValue INT)
2022-11-13 19:02:17.194 I/System.out: }
2022-11-13 19:02:17.194 I/System.out: <<<<<

2022-11-13 19:02:17.208 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@40841a6
2022-11-13 19:02:17.208 I/System.out: 0 {
2022-11-13 19:02:17.208 I/System.out:    type=table
2022-11-13 19:02:17.208 I/System.out:    name=android_metadata
2022-11-13 19:02:17.209 I/System.out:    tbl_name=android_metadata
2022-11-13 19:02:17.209 I/System.out:    rootpage=3
2022-11-13 19:02:17.209 I/System.out:    sql=CREATE TABLE android_metadata (locale TEXT)
2022-11-13 19:02:17.209 I/System.out: }
2022-11-13 19:02:17.209 I/System.out: 1 {
2022-11-13 19:02:17.210 I/System.out:    type=table
2022-11-13 19:02:17.210 I/System.out:    name=pointTable
2022-11-13 19:02:17.210 I/System.out:    tbl_name=pointTable
2022-11-13 19:02:17.211 I/System.out:    rootpage=4
2022-11-13 19:02:17.211 I/System.out:    sql=CREATE TABLE pointTable(id INTEGER PRIMARY KEY, pointValue INT)
2022-11-13 19:02:17.211 I/System.out: }
2022-11-13 19:02:17.211 I/System.out: <<<<<

关于陷阱的错误,那么上面改用的就是大错特错了

CREATE NOTAKEYWORDTABLE IF NOT EXISTS pointTable(id INTEGER PRIMARY KEY, pointValue INT)

卸载应用程序以删除现有数据库并运行结果会在日志中显示:-

2022-11-13 19:10:11.697 D/test: onCreate invoked

2022-11-13 19:10:11.697 E/SQLiteLog: (1) near "NOTAKEYWORDTABLE": syntax error in "CREATE NOTAKEYWORDTABLE IF NOT EXISTS pointTable(id INTEGER PRIMARY KEY, pointValue INT)"
2022-11-13 19:10:11.697 D/test: android.database.sqlite.SQLiteException: near "NOTAKEYWORDTABLE": syntax error (code 1 SQLITE_ERROR): , while compiling: CREATE NOTAKEYWORDTABLE IF NOT EXISTS pointTable(id INTEGER PRIMARY KEY, pointValue INT)
2022-11-13 19:10:11.701 D/test: android.database.sqlite.SQLiteException: near "NOTAKEYWORDTABLE": syntax error (code 1 SQLITE_ERROR): , while compiling: CREATE NOTAKEYWORDTABLE IF NOT EXISTS pointTable(id INTEGER PRIMARY KEY, pointValue INT)
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1045)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:652)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:61)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:33)
        at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1919)
        at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1841)
        at a.a.so74419125kotlinsqlite.SqliteHelper.onCreate(MainActivity.kt:31)
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:411)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:316)
        at a.a.so74419125kotlinsqlite.MainActivity.onCreate(MainActivity.kt:18)
        at android.app.Activity.performCreate(Activity.java:7994)
        at android.app.Activity.performCreate(Activity.java:7978)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        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)
        
        
2022-11-13 19:10:11.702 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@40841a6
2022-11-13 19:10:11.703 I/System.out: 0 {
2022-11-13 19:10:11.704 I/System.out:    type=table
2022-11-13 19:10:11.704 I/System.out:    name=android_metadata
2022-11-13 19:10:11.704 I/System.out:    tbl_name=android_metadata
2022-11-13 19:10:11.704 I/System.out:    rootpage=3
2022-11-13 19:10:11.704 I/System.out:    sql=CREATE TABLE android_metadata (locale TEXT)
2022-11-13 19:10:11.704 I/System.out: }
2022-11-13 19:10:11.704 I/System.out: <<<<<

2022-11-13 19:10:11.713 I/System.out: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@7e8b7e7
2022-11-13 19:10:11.713 I/System.out: 0 {
2022-11-13 19:10:11.713 I/System.out:    type=table
2022-11-13 19:10:11.713 I/System.out:    name=android_metadata
2022-11-13 19:10:11.713 I/System.out:    tbl_name=android_metadata
2022-11-13 19:10:11.713 I/System.out:    rootpage=3
2022-11-13 19:10:11.713 I/System.out:    sql=CREATE TABLE android_metadata (locale TEXT)
2022-11-13 19:10:11.713 I/System.out: }
2022-11-13 19:10:11.713 I/System.out: <<<<<

相关问题