gpt4 book ai didi

java - 如何转义 Java 中的撇号?

转载 作者:行者123 更新时间:2023-11-29 23:03:57 26 4
gpt4 key购买 nike

我收到以下错误消息:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kite.aomp/com.kite.aomp.MainActivity}: android.database.sqlite.SQLiteException: near "s": syntax error (code 1): , while compiling: 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();

你能帮我找到解决上述问题的方法吗?

最佳答案

您的问题正是您不应该使用这种插入数据方法的原因。
推荐的方法是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 .

关于java - 如何转义 Java 中的撇号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56718701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com