如何在Java中转义撇号?

时间:2019-06-22 19:55:41

标签: java android sqlite cursor

我收到以下错误消息:

  

java.lang.RuntimeException:无法启动活动   ComponentInfo {com.kite.aomp / com.kite.aomp.MainActivity}:   android.database.sqlite.SQLiteException:“ s”附近:语法错误(代码   1):编译时:INSERT INTO DBExample VALUES('(四月は君の嘘)Shigatsu   wa Kimi no Uso OST Collection-Watashi no Uso〜PianoSolo','〜Alex's   ShigatsuOST〜','1');

我的代码是:

    String CREATE_USER_TABLE = "CREATE TABLE DBExample " + "(" + "Title" + " VARCHAR," 
        + "Artist" + " VARCHAR," + "Numb" + " VARCHAR" + ");";

    ContentResolver musicResolver = getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
    String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
    Cursor musicCursor = musicResolver.query(musicUri, null, selection, null, sortOrder);

    SQLiteDatabase db = openOrCreateDatabase(DBNAME, MODE_PRIVATE, null);
    db.execSQL(CREATE_USER_TABLE);
    if (musicCursor != null && musicCursor.moveToFirst())
    {
        int titleColumn = musicCursor.getColumnIndex
        (android.provider.MediaStore.Audio.Media.TITLE);
        int artistColumn = musicCursor.getColumnIndex
        (android.provider.MediaStore.Audio.Media.ARTIST);

        do {

            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);

            String soj = "INSERT INTO DBExample VALUES" + "('"
                + thisTitle + "','" + thisArtist + "'," + "'1'" + ");";

            db.execSQL(soj);

        }
        while (musicCursor.moveToNext());
    }
    db.close();

您能帮我找到上述问题的解决方案吗?

1 个答案:

答案 0 :(得分:1)

您的问题正是您不应该使用此插入数据方法的原因。
推荐的方法是这样的方法insert()

ContentValues cv = new ContentValues(); 
cv.put("Title", thisTitle);
cv.put("Artist", thisArtist);
cv.put("Numb", "1");
db.insert("DBExample", null, cv);

通过使用ContentValues对象,您不必担心值的数据类型和转义单引号等特殊字符。
但是,如果您坚持使用自己的方法,则必须知道自己会冒sql injection的风险。