sqlite包含带撇号的文本

时间:2016-05-30 09:52:32

标签: android sqlite android-sqlite

我的应用程序有SQLite数据库来添加和搜索来自Web服务的字符串文本。问题是当这些字符串由撇号组成时。我搜索了它,发现我们可以改变Cursor rawQuery的方法,如posttutorial所示。但是当我尝试同样的错误时,我收到了错误。如果有人能指出我的错误,那将对我有所帮助。提前谢谢。

LogCat错误:

android.database.sqlite.SQLiteException: near "WHEREname": syntax error (code 1): , while compiling: SELECT fieldObjectId FROMlocations WHEREname = ?
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:893)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:504)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1339)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1278)
at com.sam.ubooktoday.autotextview.DatabaseHandler.checkIfExists(DatabaseHandler.java:94)
at com.sam.ubooktoday.autotextview.DatabaseHandler.create(DatabaseHandler.java:68)
at com.sam.ubooktoday.view.fragments.HomeOptionTwo$5.onResponse(HomeOptionTwo.java:175)
at com.sam.ubooktoday.view.fragments.HomeOptionTwo$5.onResponse(HomeOptionTwo.java:163)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5388)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
at dalvik.system.NativeStart.main(Native Method)

代码

public class DatabaseHandler extends SQLiteOpenHelper {

    // for our logs
    public static final String TAG = "DatabaseHandler.java";

    // database version
    private static final int DATABASE_VERSION = 5;

    // database name
    protected static final String DATABASE_NAME = "NinjaDatabase2";

    // table details
    public String tableName = "locations";
    public String fieldObjectId = "id";
    public String fieldObjectName = "name";

    // constructor
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // creating table
    @Override
    public void onCreate(SQLiteDatabase db) {

        String sql = "";

        sql += "CREATE TABLE " + tableName;
        sql += " ( ";
        sql += fieldObjectId + " INTEGER PRIMARY KEY AUTOINCREMENT, ";
        sql += fieldObjectName + " TEXT ";
        sql += " ) ";

        db.execSQL(sql);

    }


    // When upgrading the database, it will drop the current table and recreate.
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        String sql = "DROP TABLE IF EXISTS " + tableName;
        db.execSQL(sql);

        onCreate(db);
    }


    // create new record
    // @param myObj contains details to be added as single row.
    public boolean create(MyObject myObj) {

        boolean createSuccessful = false;

        if(!checkIfExists(myObj.objectName)){

            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(fieldObjectName, myObj.objectName);
            createSuccessful = db.insert(tableName, null, values) > 0;

            db.close();

            if(createSuccessful){
                Log.e(TAG, myObj.objectName + " created.");
            }
        }

        return createSuccessful;
    }

    // check if a record exists so it won't insert the next time you run this code
    public boolean checkIfExists(String objectName){

        boolean recordExists = false;

        SQLiteDatabase db = this.getWritableDatabase();
        //Cursor cursor = db.rawQuery("SELECT " + fieldObjectId + " FROM " + tableName + " WHERE " + fieldObjectName + " = '" + objectName + "'", null);

    // Here I changed my code as per tutorial
   String q = "SELECT fieldObjectId FROM" + tableName +" WHERE" +fieldObjectName+" = ?";
   Cursor cursor = db.rawQuery(q, new String[] { objectName});

        if(cursor!=null) {

            if(cursor.getCount()>0) {
                recordExists = true;
            }
        }

        cursor.close();
        db.close();

        return recordExists;
    }

    // Read records related to the search term
    public MyObject[] read(String searchTerm) {

        // select query
        String sql = "";
        sql += "SELECT * FROM " + tableName;
        sql += " WHERE " + fieldObjectName + " LIKE '%" + searchTerm + "%'";
        sql += " ORDER BY " + fieldObjectId + " DESC";
        sql += " LIMIT 0,5";

        SQLiteDatabase db = this.getWritableDatabase();

        // execute the query
        Cursor cursor = db.rawQuery(sql, null);

        int recCount = cursor.getCount();

        MyObject[] ObjectItemData = new MyObject[recCount];
        int x = 0;

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {

                String objectName = cursor.getString(cursor.getColumnIndex(fieldObjectName));
                Log.e(TAG, "objectName: " + objectName);

                MyObject myObject = new MyObject(objectName);

                ObjectItemData[x] = myObject;

                x++;

            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();

        return ObjectItemData;

    }

}

1 个答案:

答案 0 :(得分:1)

更改此行

String q = "SELECT " +fieldObjectId +" FROM " + tableName +" WHERE " +fieldObjectName+" = ?";

而不是

String q = "SELECT fieldObjectId FROM" + tableName +" WHERE " +fieldObjectName+" = ?";

删除数据库尝试此方法

   public void clearDatabase(String TABLE_NAME) 
   {  
     String clearDBQuery = "DELETE FROM "+TABLE_NAME;  
     db.execSQL(clearDBQuery);  
   }