Reputation: 421
Hello all i have this method in the database handler class and what this class do is to return the ID of the product from the product table. However, i am receiving this sqliteexception which i do not know why. Please advice thank you.
private static final String TABLE_PRODUCT = "product"
private static final String KEY_PRODUCTNAME = "productname";
public String getProductId(String productName) {
String selectQuery = "SELECT productid FROM " + TABLE_PRODUCT+ " WHERE " +KEY_PRODUCTNAME +" = " + productName;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String productid = cursor.toString();
cursor.close();
db.close();
return productid;
}
Errors:
E/AndroidRuntime(1884): FATAL EXCEPTION: main
E/AndroidRuntime(1884): android.database.sqlite.SQLiteException: unrecognized token: "Bluedress34.50" (code 1): , while compiling: SELECT productid FROM product WHERE productname = "Bluedress34.50"
my activity class:
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
String productname = pname.getText().toString();
String productQTY = pqty.getText().toString();
String productnameid = db.getUProductId(productname);
JSONObject json = userFunction.addSales(productnameid, productQty);
}
}
my userfunction class:
public JSONObject addSales(productnameid, productQty){
// Building Parameters
List<NameValuePair> paramsfile = new ArrayList();
paramsfile.add(new BasicNameValuePair("productnameid", productnameid));
paramsfile.add(new BasicNameValuePair("productQty", productQty));
JSONObject jsonfileName = jsonParser.getJSONFromUrl(addFileURL, paramsfile);
Log.e("JSON", jsonfileName.toString());
return jsonfileName;
}
Upvotes: 0
Views: 484
Reputation: 38098
I'd rather write it so:
String selectQuery =
"SELECT productid FROM " + TABLE_PRODUCT+ " WHERE " + KEY_PRODUCTNAME + " = ?";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[]{productName});
Upvotes: 4
Reputation: 12733
it just a simple mistake. you forgot to add single qoute like below:
String selectQuery = "SELECT productid FROM " + TABLE_PRODUCT+ " WHERE " +KEY_PRODUCTNAME +" = '" + productName +"'";
Upvotes: 1
Reputation: 23638
Any string value in database transactions should be accessed in '
single quote only.
Just write your product value in single quote '
as below:
" = '" + productName +"'";
Query:
"SELECT productid FROM " + TABLE_PRODUCT+ " WHERE " +KEY_PRODUCTNAME +" = '" + productName +"'";
Upvotes: 1
Reputation: 29662
Since product name is in String Format use '
in query, like below,
String selectQuery = "SELECT productid FROM " + TABLE_PRODUCT
+ " WHERE " + KEY_PRODUCTNAME +" ='" + productName +"'";
Upvotes: 5