首页 > 解决方案 > 在 java ContentValues 中转义 sqlite 列名

问题描述

我有一个 SQLite 表,其中有一列名为“组”。我试过用单引号和方括号来定界。每次,它都会插入一个没有错误消息的“0”。至少当我不理会它时,我收到一条错误消息:

2019-11-30 16:18:43.634 11008-11008/com.example.fitcardsworkouttracker E/SQLiteDatabase:错误插入名称=炒鸡蛋卡路里=78组=80份=1个鸡蛋

android.database.sqlite.SQLiteException: near "group": syntax error (code 1): , while compile: INSERT INTO foods(name,calories,group,serving) VALUES (?,?,?,?)

                ContentValues contentValues = new ContentValues();
            String newGroup = (String)tvGroup.getSelectedItem();
            Cursor c = myDatabase.rawQuery("SELECT initial FROM groups WHERE name = ?", new String[] {newGroup});
            c.moveToFirst();
            Log.i("EditHelpingDialog", "initial " + c.getInt(0));
            contentValues.put("name", foodName);
            contentValues.put("serving", etServing.getText().toString());
            contentValues.put("calories", etCalories.getText().toString());
            contentValues.put("group", (byte) c.getInt(0));

标签: javasqlitecontent-values

解决方案


GROUP是一个关键字,因此如果不转义它,您可能会遇到问题;比如你得到的语法错误。

最好不要对实体名称/标识符(列、表、触发器等)使用关键字。否则,在可能的情况下,您将不得不转义(将名称括在 []、``、"" 或 '' 之一中)。


推荐阅读