简体   繁体   English

Android 中的“/”附近的语法错误

[英]near "/" syntax error in Android

The below code in my project calls a function in my database class to insert two values into my sqlite database我项目中的以下代码调用我的数据库类中的一个函数将两个值插入到我的 sqlite 数据库中

    saveButton = (Button) findViewById(R.id.Save);
    saveButton.setOnClickListener(new View.OnClickListener( ) {
        @Override
        public void onClick(View v) {
            addCig = (EditText) findViewById(R.id.cigName );
            myDbHelper1.insertNewCig(addCig.toString(), fileName );     
        }
    });

Here is the insert into function.这是插入到函数中。 I am getting an error that reads (near "/": syntax error).我收到一个错误消息(在“/”附近:语法错误)。 Can anybody help me look into it and see what is wrong with my code.任何人都可以帮我调查一下,看看我的代码有什么问题。

public void insertNewCig(String name, String file)
{
    //DB_PATH = "/data/data/com.example.newdb/databases/"
    //DB_NAME = "cigarettes"
    String myPath = DB_PATH + DB_NAME;
    String row1 = "INSERT INTO " + myPath + " (" + KEY_FIRST + ", " +  KEY_LAST + ") VALUES(" + name + ", " + file + ")";
    myDataBase.execSQL(row1);

}

myPath should be the name of a table in your database, not the name and path of the database file. myPath应该是数据库中表的名称,而不是数据库文件的名称和路径。 You also need to add single quotes around the values you are inserting, otherwise SQLite won't recognize that they are literal string values and not something else (eg column names).您还需要在要插入的值周围添加单引号,否则 SQLite 将无法识别它们是文字字符串值而不是其他内容(例如列名)。 This is one of many reasons not to try to build raw SQL statements by hand in code.这是不尝试在代码中手动构建原始 SQL 语句的众多原因之一。

Since you have a SQLiteDatabase , you may as well use its insert() methods instead of execSQL() .由于您有一个SQLiteDatabase ,您也可以使用它的insert()方法而不是execSQL() In that case you would give it a ContentValues instead of constructing a raw statement, which obviates the need to wrap the string values with single quotes.在这种情况下,您将给它一个ContentValues而不是构造一个原始语句,这样就不需要用单引号包裹字符串值。

ContentValues values = new ContentValues();
values.put(KEY_FIRST, name);
values.put(KEY_LAST, file);
myDataBase.insert(TABLE_NAME, null, values);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM